javascript

您所在的位置:网站首页 瞎扯淡的由来 javascript

javascript

2023-06-30 07:43| 来源: 网络整理| 查看: 265

sleep函数,顾名思义,等待一段时间后再执行

1,异步sleep,等待期间其他代码继续执行

function sleep(time, callback) { setTimeout(callback, time) } console.warn('sleep start') //sleep 1s sleep(1000, () => { console.log('sleep callback') }) console.warn('code end')

promise写法

function sleep (time) { return new Promise((resolve) => setTimeout(resolve, time)); } // 用法 console.warn('sleep start') sleep(3000).then(() => { console.log('sleep callback') }) console.warn('code end')

2,同步sleep,等待期间中断代码执行

function sleep (time) { return new Promise((resolve) => setTimeout(resolve, time)); } (async function() { console.warn('sleep start'); await sleep(3000); console.log('sleep callback') console.warn('code end') })();


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3