Javascript sleep/delay/wait function

后端 未结 6 1225
时光取名叫无心
时光取名叫无心 2021-01-03 23:13

Sorry if this question has already been asked here before, I could not find a suitable answer.

I am wanting to create a JavaScript sleep/delay/wait function that I c

6条回答
  •  长发绾君心
    2021-01-04 00:03

    Here's a solution using the new async/await syntax.

    async function testWait() {
        alert('going to wait for 5 second');
        await wait(5000);
        alert('finally wait is over');
    }
    
    function wait(time) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve();
            }, time);
        });
    }
    

    Note: You can call function wait only in async functions

提交回复
热议问题