Synchronous delay in code execution

前端 未结 10 1193
长情又很酷
长情又很酷 2020-12-03 02:29

I have a code which needs to be executed after some delay say 5000 ms.Currently I am using setTimeout but it is asynchronous and i want the execution to wait for its return.

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 03:19

    Synchronous wait (only for testing!):

    const syncWait = ms => {
        const end = Date.now() + ms
        while (Date.now() < end) continue
    }
    

    Usage:

    console.log('one')
    syncWait(5000)
    console.log('two')
    

    Asynchronous wait:

    const asyncWait = ms => new Promise(resolve => setTimeout(resolve, ms))
    

    Usage:

    (async () => {
        console.log('one')
        await asyncWait(5000)
        console.log('two')
    })()
    

    Alternative (asynchronous):

    const delayedCall = (array, ms) =>
        array.forEach((func, index) => setTimeout(func, index * ms))
    

    Usage:

    delayedCall([
        () => console.log('one'),
        () => console.log('two'),
        () => console.log('three'),
    ], 5000)
    

提交回复
热议问题