Sleep in JavaScript - delay between actions

前端 未结 11 1862
别跟我提以往
别跟我提以往 2020-11-22 01:27

Is there a way I can do a sleep in JavaScript before it carries out another action?

Example:

 var a = 1+3;
 // Sleep 3 seconds before the next action         


        
11条回答
  •  借酒劲吻你
    2020-11-22 02:20

    There are several ways to solve this problem. If we use the setTimeout function, let's get to know it first. This function has three parameters: function or code, delay (in milliseconds) and the parameters. Since the function or code parameter is required, the others are optional. Once you have not entered the delay, it will be set to zero.

    For more details about the setTimeout() go to this link.

    Simplified version:

    var a = 1 + 3;
    var b;
    console.log('a = ' + a);
    setTimeout(function(){ 
        b = a + 4; 
        console.log('b = ' + b);
    }, 1000);
    

    output:
    a = 4
    24       --> Number identifier of the list of active timeouts
    b = 8


    Using the parameter pass:

    var a = 1 + 3;
    var b;
    console.log('a = ' + a);
    setTimeout(myFunction, 1000, a);
    
    function myFunction(a)
    {
        var b = a + 4;
        console.log('b = ' + b);
    }
    

    output:
    a = 4
    25       --> Number identifier of the list of active timeouts
    b = 8



    Browser Support:

    Chrome     Firefox     Edge     Safari     Opera
    1.0        1.0         4.0      1.0        4.0
    

提交回复
热议问题