Javascript版本的sleep()
转自 https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
# 1
这个问题回答下面赞数最高的回答很好用(比如可以用在循环当中),#2是比较久远的方法,在循环当中使用可能会出问题导致死循环。
关键是async和await两个关键字。
function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function demo() { console.log('Taking a break...'); await sleep(2000); console.log('Two seconds later, showing sleep in a loop...'); // Sleep in loop for (let i = 0; i < 5; i++) { if (i === 3) await sleep(2000); console.log(i); } } demo();
Note that
await
can only be executed in functions prefixed with theasync
keyword, or at the top level of your script in an increasing number of environments.await
only pauses the currentasync
function. This means it's not blocking the execution of the rest of the script, which is what you want in the vast majority of the cases. If you do want a blocking construct, see this answer usingAtomics
.wait
, but note that most browsers will not allow it on the browser's main thread.
Two new JavaScript features (as of 2017) helped write this "sleep" function:
- Promises, a native feature of ES2015 (aka ES6). We also use arrow functions in the definition of the sleep function.
- The
async/await
feature lets the code explicitly wait for a promise to settle (resolve or reject).
Compatibility
- promises are supported in Node v0.12+ and widely supported in browsers, except IE
async
/await
landed in V8 and has been enabled by default since Chrome 55 (released in Dec 2016)- it landed in Node 7 in October 2016
- and also landed in Firefox Nightly in November 2016
If for some weird reason you're using Node older than 7 (which has reached end of life), or are targeting old browsers, async
/await
can still be used via Babel (a tool that will transpile JavaScript + new features into plain old JavaScript), with the transform-async-to-generator
plugin.
#2
比较旧的方法。缺点是在循环中使用会出现无限循环。
function sleep (time) { return new Promise((resolve) => setTimeout(resolve, time)); } sleep(2000).then(() => { function; })
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步