Home > Web Front-end > JS Tutorial > How to Pause JavaScript Execution for 5 Seconds Before Evaluating a Condition?

How to Pause JavaScript Execution for 5 Seconds Before Evaluating a Condition?

DDD
Release: 2024-11-02 00:16:31
Original
215 people have browsed it

How to Pause JavaScript Execution for 5 Seconds Before Evaluating a Condition?

A Pause in Execution: Implementing a 5-Second Wait

In your JavaScript code, you're encountering an issue with the timing of a certain function. You aim to delay the execution of a code block for 5 seconds before evaluating a condition.

The code you've provided:

<code class="js">function stateChange(newState) {
  setTimeout('', 5000);

  if(newState == -1) {
    alert('VIDEO HAS STOPPED');
  }
}</code>
Copy after login

doesn't achieve your desired behavior because the setTimeout function doesn't actually delay the execution of the if statement. Instead, it schedules a callback function to be executed after 5000 milliseconds, but the if statement is executed immediately.

To resolve this, you can leverage asynchronous programming techniques in JavaScript, which provide a way to pause execution flow and resume it later. Here are two approaches that can address your requirement:

Browser-based Solution

<code class="js">const delay = ms => new Promise(res => setTimeout(res, ms));

async function stateChange(newState) {
  await delay(5000);
  console.log("Waited 5s before checking condition");

  if (newState == -1) {
    alert('VIDEO HAS STOPPED');
  }
}</code>
Copy after login

In this solution, we define a utility function called delay that creates a promise that resolves after the specified number of milliseconds. The async keyword is used to make the stateChange function asynchronous, allowing it to pause execution until the promise resolves.

Node.js Solution

<code class="js">const { setTimeout } = require("timers/promises");

async function stateChange(newState) {
  await setTimeout(5000);
  console.log("Waited 5s before checking condition");

  if (newState == -1) {
    alert('VIDEO HAS STOPPED');
  }
}</code>
Copy after login

This solution utilizes Node.js's built-in setTimeout function that returns a promise, allowing you to pause execution until the promise is resolved. The async keyword is used as in the previous example.

The above is the detailed content of How to Pause JavaScript Execution for 5 Seconds Before Evaluating a Condition?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template