Home > Web Front-end > JS Tutorial > body text

How to Wait 5 Seconds Before Executing the Next Line in JavaScript?

Mary-Kate Olsen
Release: 2024-10-26 07:01:31
Original
226 people have browsed it

How to Wait 5 Seconds Before Executing the Next Line in JavaScript?

Wait 5 Seconds Before Executing Next Line

In JavaScript, the setTimeout() function schedules a function to be executed after a specified number of milliseconds. However, it does not halt the execution of the code, meaning that the next line of code will be executed immediately after the setTimeout() call, regardless of the specified delay.

Your Code

Your code aims to wait 5 seconds before checking if newState is equal to -1. However, since setTimeout() does not block the code, the checking happens immediately, before the 5-second delay occurs.

Solution

To achieve the desired behavior, you need to use a mechanism that can pause the execution of your code for 5 seconds. There are two modern approaches you can consider:

1. Async/Await Syntax (Browser Only)

ES6 introduced the async/await syntax, which allows you to write asynchronous code in a more synchronous style. By marking your function as async, you can use the await keyword to pause execution until a promise is resolved.

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

const stateChange = async newState => {
  await delay(5000);

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

2. Timers/Promises Module (Node.js Only)

In Node.js 16, the timers/promises module provides a promise-based version of setTimeout. This allows you to pause execution and wait for the delay to complete before continuing.

<code class="javascript">import { setTimeout } from "timers/promises";

const stateChange = async newState => {
  await setTimeout(5000);

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

Both of these approaches will ensure that the code execution is halted for 5 seconds before the newState check is performed.

The above is the detailed content of How to Wait 5 Seconds Before Executing the Next Line in JavaScript?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!