Sleep in JavaScript - delay between actions

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

    If you want less clunky functions than setTimeout and setInterval, you can wrap them in functions that just reverse the order of the arguments and give them nice names:

    function after(ms, fn){ setTimeout(fn, ms); }
    function every(ms, fn){ setInterval(fn, ms); }
    

    CoffeeScript versions:

    after = (ms, fn)-> setTimeout fn, ms
    every = (ms, fn)-> setInterval fn, ms
    

    You can then use them nicely with anonymous functions:

    after(1000, function(){
        console.log("it's been a second");
        after(1000, function(){
            console.log("it's been another second");
        });
    });
    

    Now it reads easily as "after N milliseconds, ..." (or "every N milliseconds, ...")

提交回复
热议问题