Sleep in JavaScript - delay between actions

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

    You can use setTimeout to achieve a similar effect:

    var a = 1 + 3;
    var b;
    setTimeout(function() {
        b = a + 4;
    }, (3 * 1000));
    

    This doesn't really 'sleep' JavaScript—it just executes the function passed to setTimeout after a certain duration (specified in milliseconds). Although it is possible to write a sleep function for JavaScript, it's best to use setTimeout if possible as it doesn't freeze everything during the sleep period.

    0 讨论(0)
  • 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');
    }

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

    Another way to do it is by using Promise and setTimeout (note that you need to be inside a function and set it as asynchronous with the async keyword) :

    async yourAsynchronousFunction () {
    
        var a = 1+3;
    
        await new Promise( (resolve) => {
            setTimeout( () => { resolve(); }, 3000);
        }
    
        var b = a + 4;
    
    }
    
    0 讨论(0)
  • 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.

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

    You can use plain javascript, this will call your function/method after 5 seconds:

    setTimeout(()=> { your_function(); }, 5000);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题