What's the best way to implement a sleep function JavaScript? [duplicate]

别等时光非礼了梦想. 提交于 2019-12-01 22:01:24
Daniel Vassallo

What's the best way to implement a sleep function JavaScript?

JavaScript code has to be non-blocking, because any code that blocks, like a loop that waits for something to happen, will make the whole browser unresponsive. JavaScript in web browsers not only runs in a single thread, but it actually shares the same thread with the page rendering and UI.

The solution is to use timers: setTimeout() or setInterval(). These functions are non-blocking; they return immediately. They attach a callback function to a timeout event that will get triggered some time in the future. The JavaScript code terminates execution soon after the setTimeout() function is called, so the users would still be able to use the browser. Then when the timeout is triggered, the previously defined callback is invoked, and your code is interpreted. This is the only practical way to handle "delays" in JavaScript.

In addition, here's an interesting article on how JavaScript timers work:


Now that you know why a blocking sleep function won't work, check out @Tomalak's link for a few solutions using setTimeout() or setInterval().

Tomalak

This is quite simple and also has been answered before. See the answers to this question:

You're complaining about setTimeout and setInterval, but then describing how you are using them badly. Either user setTimeout not in a loop and have it call another setTimeout if there is more to do, or use setInterval and call clearInterval after a maintained count is reached.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!