delay one second in JavaScript

Question

Answers ( 1 )

    0
    2024-01-16T19:14:49+00:00

    It's a query about implementing a delay or pause in the execution of JavaScript code.

    To introduce a delay of one second in JavaScript, you typically use the setTimeout function. This function schedules code to run after a specified number of milliseconds. Since there are 1000 milliseconds in a second, you would set it to 1000 for a one-second delay. Here are a couple of common ways to use setTimeout:

    Basic Usage

    setTimeout(function() {
        // Your code here will execute after 1 second
        console.log("This message is shown after 1 second");
    }, 1000);
    

    In this example, the message in console.log will be displayed after a delay of one second.

    With ES6 Arrow Functions

    If you are using ES6, you can make use of arrow functions for a more concise syntax:

    setTimeout(() => {
        // Your code here will execute after 1 second
        console.log("This message is shown after 1 second");
    }, 1000);
    

    Asynchronous Functions

    In modern JavaScript, especially in the context of asynchronous operations, you might want to use setTimeout with Promises or async/await for better flow control:

    function delay(duration) {
      return new Promise(resolve => setTimeout(resolve, duration));
    }
    
    // Usage with async/await
    async function run() {
        console.log("Start");
        await delay(1000); // Wait 1 second
        console.log("One second later");
    }
    
    run();
    

    In this case, the delay function returns a Promise that resolves after the specified duration, making it easy to use with async/await syntax for clearer, more linear-looking asynchronous code.

    Note

    It's important to remember that JavaScript is generally non-blocking, and setTimeout doesn't actually "pause" the execution of subsequent code. It schedules the function inside it to run after the delay, while the rest of the code continues to execute.

Leave an answer