Sleep in JavaScript - delay between actions

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

    ECMAScript 6 version, using generators with yield for "code blocking":

    Because the original question was posted seven years ago, I didn't bother answering with the exact code, because it's just way too easy and already answered. This should help in more complicated problems, like if you need at least two sleeps, or if you are planning to sequence asynchronous execution. Feel free to modify it to fit your needs.

    let sleeptime = 100
    function* clock()
    {
        let i = 0
        while( i <= 10000 )
        {
            i++
            console.log(i); // actually, just do stuff you wanna do.
            setTimeout(
                ()=>
                {
                    clk.next()
                }
                , sleeptime
            )
            yield
        }
    }
    
    let clk = clock()
    clk.next()

    function*

    () => arrow function

    You can also chain events via Promises:

    function sleep(ms)
    {
        return(
            new Promise(function(resolve, reject)
            {
                setTimeout(function() { resolve(); }, ms);
            })
        );
    }
    
    
    sleep(1000).then(function()
    {
        console.log('1')
        sleep(1000).then(function()
        {
            console.log('2')
        })
    })

    Or much simpler and a less fancy way would be

    function sleep(ms, f)
    {
        return(
            setTimeout(f, ms)
        )
    }
    
    
    sleep(500, function()
    {
        console.log('1')
        sleep(500, function()
        {
            console.log('2')
        })
    })
    console.log('Event chain launched')

    If you're just waiting for some condition to happen you can wait like this

    function waitTill(condition, thenDo)
    {
        if (eval(condition))
        {
            thenDo()
            return
        }
    
        setTimeout(
            ()    =>
            {
                waitTill(condition, thenDo)
            }
            ,
            1
        )
    }
    
    x=0
    
    waitTill(
        'x>2 || x==1'
        ,
        ()    =>
        {
            console.log("Conditions met!")
        }
    )
    
    // Simulating the change
    setTimeout(
        () =>
        {
            x = 1
        }
        ,
        1000
    )

    0 讨论(0)
  • 2020-11-22 02:15

    This is my model that shows how to "sleep" or "DoEvents" in javascript using a generator function (ES6). Commented code:

    <html>
    <head>
    <script>
      "use strict"; // always
      // Based on post by www-0av-Com https://stackoverflow.com/questions/3143928
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
      var divelt, time0, globaln = 0; // global variables
      var MainGenObj = Main(); // generator object = generator function()
    window.onload = function() {
      divelt = document.getElementsByTagName("body")[0]; // for addline()
      addline("typeof Main: " + typeof Main);
      addline("typeof MainDriver: " + typeof MainDriver);
      addline("typeof MainGenObj: " + typeof MainGenObj);
      time0 = new Date().valueOf(); // starting time ms
      MainDriver(); // do all parts of Main()
    }
    function* Main() { // this is "Main" -- generator function -- code goes here
      // could be loops, or inline, like this:
    
      addline("Part A, time: " + time() + ", " + ++globaln); // part A
      yield 2000;                    // yield for 2000 ms (like sleep)
    
      addline("Part B, time: " + time() + ", " +  ++globaln); // part B
      yield 3000;                    // yield for 3000 ms (or like DoEvents)
    
      addline("Part Z, time: " + time() + ", " +  ++globaln); // part Z (last part)
      addline("End, time: " + time());
    }
    function MainDriver() { // this does all parts, with delays
      var obj = MainGenObj.next(); // executes the next (or first) part of Main()
      if (obj.done == false) { // if "yield"ed, this will be false
        setTimeout(MainDriver, obj.value); // repeat after delay
      }
    }
    function time() { // seconds from time0 to 3 decimal places
      var ret = ((new Date().valueOf() - time0)/1000).toString();
      if (ret.indexOf(".") == -1) ret += ".000";
      while (ret.indexOf(".") >= ret.length-3) ret += "0";
      return ret;
    }
    function addline(what) { // output
      divelt.innerHTML += "<br />\n" + what;
    }
    </script>
    </head>
    <body>
    <button onclick="alert('I\'m alive!');"> Hit me to see if I'm alive </button>
    </body>
    </html>
    
    0 讨论(0)
  • 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, ...")

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:20

    There are several ways to solve this problem. If we use the setTimeout function, let's get to know it first. This function has three parameters: function or code, delay (in milliseconds) and the parameters. Since the function or code parameter is required, the others are optional. Once you have not entered the delay, it will be set to zero.

    For more details about the setTimeout() go to this link.

    Simplified version:

    var a = 1 + 3;
    var b;
    console.log('a = ' + a);
    setTimeout(function(){ 
        b = a + 4; 
        console.log('b = ' + b);
    }, 1000);
    

    output:
    a = 4
    24       --> Number identifier of the list of active timeouts
    b = 8


    Using the parameter pass:

    var a = 1 + 3;
    var b;
    console.log('a = ' + a);
    setTimeout(myFunction, 1000, a);
    
    function myFunction(a)
    {
        var b = a + 4;
        console.log('b = ' + b);
    }
    

    output:
    a = 4
    25       --> Number identifier of the list of active timeouts
    b = 8



    Browser Support:

    Chrome     Firefox     Edge     Safari     Opera
    1.0        1.0         4.0      1.0        4.0
    
    0 讨论(0)
提交回复
热议问题