Sleep in JavaScript - delay between actions

前端 未结 11 1867
别跟我提以往
别跟我提以往 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:00

    You can use setTimeout to achieve a similar effect:

    var a = 1 + 3;
    var b;
    setTimeout(function() {
        b = a + 4;
    }, (3 * 1000));
    

    This doesn't really 'sleep' JavaScript—it just executes the function passed to setTimeout after a certain duration (specified in milliseconds). Although it is possible to write a sleep function for JavaScript, it's best to use setTimeout if possible as it doesn't freeze everything during the sleep period.

提交回复
热议问题