Implementing the sleep function is an exam question that examines the basic skills of a candidate's JS. Let's explore this question together~
Method 1: Use Promise + then
Set the timer through setTimout in Promise, and execute the callback through then.
// 使用Promise实现sleep
const sleep = time => {
return new Promise(resolve => {
setTimeout(resolve,time)
})
}
var start = new Date().getTime();
sleep(2000).then(() => {
console.log(1);
var end = new Date().getTime();
console.log(end-start+'ms'); // 2004ms
})
Method 2: Use generator function + then
Return a Promise via the yield keyword of the generator function, and then call it via next().value.then.
function* sleep(time) {
yield new Promise(resolve => {
setTimeout(resolve, time)
})
}
var start = new Date().getTime();
sleep(2000).next().value.then(() => {
console.log(1);
var end = new Date().getTime();
console.log(end - start + 'ms'); // 2003ms
})
Method 3: Use async + await
The async + await method can implement asynchronous blocking tasks.
function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time)
})
}
var start = new Date().getTime();
async function output() {
await sleep(2000);
var end = new Date().getTime();
console.log(end - start + 'ms'); // 2002ms
}
output()
Method 4: Implement directly through setTimeout
function sleep(callback,time) {
setTimeout(callback,time);
}
const start = new Date().getTime();
function output() {
console.log(111);
const end = new Date().getTime();
console.log(`${
end - start} ms`); // 2006 ms
}
sleep(output,2000)
RQ: Why is there a time error after the timer is executed?
Because setTimeout belongs to a macro task, there may be errors in how the task being executed in the current execution stack exceeds the time set by the timer before executing the macro task.