Sleep in JavaScript - delay between actions

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

    2018 Update

    The latest Safari, Firefox and Node.js are now also supporting async/await/promises.

    Using async/await/Promises:

    (As of 1/2017, supported on Chrome, but not on Safari, Internet Explorer, Firefox, Node.js)

    'use strict';
    
    function sleep(ms) {
      return new Promise(res => setTimeout(res, ms));
    }
    
    let myAsyncFunc = async function() {
      console.log('Sleeping');
      await sleep(3000);
      console.log('Done');
    }
    
    myAsyncFunc();

    2017 Update

    JavaScript has evolved since this question was asked and now has generator functions, and the new async/await/Promise is being rolled out. Below there are two solutions, one with generator function that will work on all modern browsers, and another, using the new async/await that is not yet supported everywhere.

    Using a generator function:

    'use strict';
    
    let myAsync = (g) => (...args) => {
        let f, res = () => f.next(),
            sleep = (ms) => setTimeout(res, ms);
        f = g.apply({sleep}, args); f.next();
    };
    
    let myAsyncFunc = myAsync(function*() {
        let {sleep} = this;
        console.log("Sleeping");
        yield sleep(3000);
        console.log("Done");
    });
    
    myAsyncFunc();

    Pay attention to the fact that both these solutions are asynchronous in nature. This means that the myAsyncFunc (in both cases) will return while sleeping.

    It is important to note that this question is different than What is the JavaScript version of sleep()? where the requestor is asking for real sleep (no other code execution on the process) rather than a delay between actions.

提交回复
热议问题