Home >Web Front-end >JS Tutorial >How can I create a 5-second delay in JavaScript before executing the next line of code?
When working in JavaScript, controlling the flow of execution is paramount. Consider the following scenario: you need a function to pause for 5 seconds before executing a specific action, such as checking a variable's value.
Traditionally, JavaScript developers have relied on the setTimeout function to introduce delays in execution. This function takes two parameters: a string representing the code to execute and a delay expressed in milliseconds. In your particular case, the code excerpt below falls short:
<br>function stateChange(newState) {<br> setTimeout('', 5000);</p> <p>if (newState == -1) {</p> <pre class="brush:php;toolbar:false">alert('VIDEO HAS STOPPED');
}
}
The issue here is that the empty string passed to setTimeout doesn't have any effect. To create a 5-second delay before checking the newState variable, you should modify the code as follows:
<br>function stateChange(newState) {<br> setTimeout(() => {</p> <pre class="brush:php;toolbar:false">if (newState == -1) { alert('VIDEO HAS STOPPED'); }
}, 5000);
}
By providing a function as the first argument, you specify the code to be executed after the delay. Now, the function will accurately pause for 5 seconds before checking the newState.
In modern JavaScript, you can also leverage async/await to achieve the same result. Async/await simplifies asynchronous operations and makes your code more readable. Here's how to implement it for your scenario:
<br>const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));</p> <p>async function stateChange(newState) {<br> await delay(5000);</p> <p>if (newState == -1) {</p> <pre class="brush:php;toolbar:false">alert('VIDEO HAS STOPPED');
}
}
This code employs the delay function, which returns a Promise that resolves after the specified delay. By using async/await, you declare the stateChange function as an asynchronous function and await the completion of the delay, ensuring the 5-second pause before checking the newState.
The above is the detailed content of How can I create a 5-second delay in JavaScript before executing the next line of code?. For more information, please follow other related articles on the PHP Chinese website!