在 javascript 中睡眠(或等效)
如何在执行下一个函数之前等待 1 秒?
例如 php 有 sleep()
How do I wait 1 second before executing next function?
For example like php has sleep()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
setTimeout(f, 1000);
设置 1000 毫秒后运行函数的超时
window.setTimeout
[文档]window.setTimeout
[规范]window.setTimeout
[黑暗面]正如评论中提到的。 JavaScript 是单线程的,该线程与浏览器 UI 线程共享。
因此,通过调用诸如
sleep
之类的阻塞函数。您将阻塞唯一线程。这也意味着客户端在阻塞时无法与页面交互。请参阅事件驱动编程[wiki]< /a> 文章了解更多信息
setTimeout(f, 1000);
Set a timeout to run a function after 1000 milliseconds
window.setTimeout
[docs]window.setTimeout
[spec]window.setTimeout
[dark side]As mentioned in the comments. JavaScript is single threaded and that thread is shared with the browser UI thread.
So by calling a blocking function like
sleep
. You would block the only thread. This also means that the client cannot interact with the page whilst it is blocking.See the Event Driven Programming[wiki] article for more information
尽管所有主流浏览器都支持 setTimeout,但我更喜欢使用 javascript 库,因为通常执行的 js 操作比调用超时函数要多。在 YUI 中:
更多信息此处。
Even though setTimeout is supported in all major browsers, I prefer to use a javascript library because usually one is doing more js than just calling a timeout function. In YUI its:
More information here.
您可以使用 setTimeOut 方法来执行此操作
http://www.w3schools.com/js/js_timing.asp
You can use setTimeOut method to do so
http://www.w3schools.com/js/js_timing.asp