Sleep in JavaScript - delay between actions

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

    Try this function:

    const delay = (ms, cb) => setTimeout(cb, ms)
    

    Here is how you use it:

    console.log("Waiting for 5 seconds.")
    delay(5000, function() {
      console.log("Finished waiting for 5 seconds.")
    })
    

    Or go promise style:

    const delay = ms => new Promise(resolve => {
        setTimeout(resolve, ms)
    })
    

    Here's a demo.

提交回复
热议问题