|
睡眠函数
比如 sleep(1000)代表等待 1000ms
方法一:ES5 方式实现
function sleep(callback, time) {
if (typeof callback == "function") {
setTimeout(callback, time);
}
}
function output() {
console.log(1);
}
sleep(output, 2000);
方法二:使用 promise 方式
const sleep = (time) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
};
sleep(2000).then(() => {
console.log(1);
});
方法三:利用 async
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function init() {
var temp = await sleep(2000);
console.log("YJJ"); //2s后执行
}
init();
程序猿的技术大观园:www.javathinker.net
|
|