Sleep in JavaScript - delay between actions

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

    Another way to do it is by using Promise and setTimeout (note that you need to be inside a function and set it as asynchronous with the async keyword) :

    async yourAsynchronousFunction () {
    
        var a = 1+3;
    
        await new Promise( (resolve) => {
            setTimeout( () => { resolve(); }, 3000);
        }
    
        var b = a + 4;
    
    }
    

提交回复
热议问题