Home >Web Front-end >JS Tutorial >How Can I Delay Code Execution for 5 Seconds After Setting a Timeout?
The provided code attempts to delay the execution of an operation by 5 seconds using the setTimeout function:
<code class="javascript">function stateChange(newState) { setTimeout('', 5000); if(newState == -1) { alert('VIDEO HAS STOPPED'); } }</code>
However, the code immediately checks for the condition newState == -1 after scheduling the timeout, defeating the intended delay.
A proper solution involves utilizing asynchronous programming techniques to defer the execution of the if statement until after 5 seconds have passed. For browsers, you can use the async/await syntax:
<code class="javascript">// Utility function const delay = ms => new Promise(res => setTimeout(res, ms)); // Function to wait 5 seconds before checking newState const stateChange = async (newState) => { await delay(5000); if (newState == -1) { alert('VIDEO HAS STOPPED'); } };</code>
For Node.js 16 and above, you can take advantage of the built-in promise-based setTimeout:
<code class="javascript">import { setTimeout } from "timers/promises"; const stateChange = async (newState) => { await setTimeout(5000); if (newState == -1) { alert('VIDEO HAS STOPPED'); } };</code>
Remember to check browser support for async/await and Node.js version for the built-in promise-based setTimeout.
The above is the detailed content of How Can I Delay Code Execution for 5 Seconds After Setting a Timeout?. For more information, please follow other related articles on the PHP Chinese website!