Sleep in JavaScript - delay between actions

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

    Here's a very simple way to do it that 'feels' like a synchronous sleep/pause, but is legit js async code.

    // Create a simple pause function
    const pause = (timeoutMsec) => new Promise(resolve => setTimeout(resolve,timeoutMsec))
    
    async function main () {
        console.log('starting');
        // Call with await to pause.  Note that the main function is declared asyc
        await pause(3*1000)
        console.log('done');
    }

提交回复
热议问题