js实现 delay 和 sleep函数
作者:互联网
console.log("====sleep==="); // sleep 等待几秒 const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds)); async function sleepTest() { console.log("start"); await sleep(1000); console.log("stop"); } sleepTest(); console.log("====delay==="); // delay 延迟几秒后执行函数 function delay(fn, seconds, ...args) { return new Promise((resolve) => setTimeout(() => { // console.log(args); Promise.resolve(fn(...args)).then(resolve); }, seconds) ); } async function delayTest() { console.log("Start"); await delay( (...args) => { console.log("delay log", ...args); }, 1000, "aa", "bb", "cc", "dd" ); console.log("stop"); } delayTest();
sleep 即等待几秒后再执行下一个逻辑
delay 即几秒之后执行具体的方法,执行结束之后,再执行下一个逻辑
标签:resolve,console,log,args,js,delay,sleep 来源: https://www.cnblogs.com/beileixinqing/p/16597265.html