实现睡眠功能JavaScript的最佳方法是什么? [英] What's the best way to implement a sleep function JavaScript?

查看:103
本文介绍了实现睡眠功能JavaScript的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 setInterval setTimeout 函数,但它不适合我的情况,因为我需要在7秒的间隔内创建 img DOM元素。

I'm aware of both setInterval and setTimeout functions but it's not suitable for my case, because I need to create an img DOM element in the interval of 7 seconds.


  • 计数图像未预定义(每天不同)。

当我使用 setInterval ,我不能完全在一定限度(每日计数)后停止它。 [ clearInterval 仅清除迭代次数]

When I use setInterval, I cannot completely stop it after certain limit (daily count). [clearInterval clears iterations only]

当我使用 setTimeout 内循环(每日计数),它永远不会延迟。所以唯一的可能是睡眠功能。任何人都可以帮助解决这种情况吗?

When I use setTimeout inside loop (daily count), it never delays. So the only possibility is a sleep function. Can anyone help for this situation?


  • 实现睡眠功能JavaScript的最佳方法是什么?

推荐答案


实现睡眠功能的最佳方法是什么? ?

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

JavaScript代码必须是非阻塞的,因为任何阻塞的代码,如等待某事发生的循环,都将使整个浏览器无响应。 Web浏览器中的JavaScript不仅在单个线程中运行,而且实际上与页面呈现和UI共享相同的线程。

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.

解决方案是使用定时器: setTimeout() 或< a href =https://developer.mozilla.org/en/DOM/window.setInterval =nofollow noreferrer> setInterval() 。这些功能是非阻塞的;他们马上回来。它们将回调函数附加到将在未来某个时间触发的超时事件。在调用 setTimeout()函数后,JavaScript代码很快就会终止执行,因此用户仍然可以使用浏览器。然后,当触发超时时,将调用先前定义的回调,并解释您的代码。这是处理JavaScript中延迟的唯一实用方法。

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.

此外,这是一篇关于JavaScript定时器如何工作的有趣文章:

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

  • How JavaScript Timers Work by John Resig

现在您知道为什么阻塞睡眠功能不起作用,请查看@Tomalak的链接,了解使用 setTimeout()或<的一些解决方案code> setInterval()

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().

这篇关于实现睡眠功能JavaScript的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆