Home  >  Article  >  Web Front-end  >  How Can I Delay Code Execution for 5 Seconds After Setting a Timeout?

How Can I Delay Code Execution for 5 Seconds After Setting a Timeout?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 03:26:27275browse

How Can I Delay Code Execution for 5 Seconds After Setting a Timeout?

Deferring Code Execution for 5 Seconds

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.

Browser/Node.js Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn