Sleep in JavaScript - delay between actions

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

    In case you really need a sleep() just to test something. But be aware that it'll crash the browser most of the times while debuggin - probably that's why you need it anyway. In production mode I'll comment out this function.

    function pauseBrowser(millis) {
        var date = Date.now();
        var curDate = null;
        do {
            curDate = Date.now();
        } while (curDate-date < millis);
    }
    

    Don't use new Date() in the loop, unless you want to waste memory, processing power, battery and possibly the lifetime of your device.

提交回复
热议问题