Sleep in JavaScript - delay between actions

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

提交回复
热议问题