问题描述
假设由于某种奇怪的原因我想阻止 Javascript 执行一段时间,我该怎么做.JS 中没有 sleep().请不要说做一个 while() 循环,因为那很糟糕.我可以做一个 window.showModalDialog 并将一个 window.close 放在模态对话框中,setTimeout 的时间非常短,这样用户就不会注意到对话框.这就像一小段时间的睡眠,如果需要,我可以多次调用它.还有其他方法吗?
Suppose I want to block Javascript execution for certain time for some weird reason, how can I do that. There is no sleep() in JS. Pls don't say do a while() loop because that's bad. I can do a window.showModalDialog and put a window.close in the modal dialog with setTimeout of very small time so that the user doesn't notice the dialog. This will be like sleep for small time period and I can call this multiple time if needed. Is there some other way?
详细地说,我的用例是 HTML5 SQL 数据库提供了异步 api,但我想将它用于存储永远不会很大的小型 web 应用程序.所以不需要异步 api,因为小型存储上的查询将在客户端运行.所以我想写一个带有sync api的ORM,这样开发者可以更方便地使用它.为了将此异步连接到同步 api,我需要睡眠之类的东西.
To elaborate, my use case is that HTML5 SQL Database has given async api's but I want to use it for a samll webapp for which the store will never be big. So there is no need of an async api because the queries on the small store will run on the client side. So I want to write an ORM with sync api so that developers can use it more easily. To bridge this async to sync api, I need something like sleep.
推荐答案
window.setTimeout
或 window.setInterval
几乎是你唯一的朋友.
window.setTimeout
or window.setInterval
are pretty much your only friends.
如何使用setTimeout
递归调用设置另一个超时的函数的示例如下
An example of how to use setTimeout
to recursively call a function that sets another timeout is as follows
function go() {
if (go.count < 4) {
// logs 1, 2, 3 to firebug console at 1 second intervals
console.log(go.count++);
window.setTimeout(go, 1000);
}
}
go.count = 1;
go();
您可以选择捕获 timeoutID 以用于 window.clearTimeout
如果您需要在超时完成之前清除它.
You may choose to capture the timeoutID to use with window.clearTimeout
if you need to clear the timeout prior to it finishing.
请注意,window.setTimeout
和 window.setInterval
阻止执行其他脚本 - 我不这样做不相信以当前的形式使用 JavaScript 是可能的.有一些方法可以通过编码来模拟 UI 阻塞,例如使用 showModalDialog
或使用一些全局的 blocking
布尔值,这恐怕是你所能得到的.
Note that neither window.setTimeout
nor window.setInterval
block execution of other script - I don't believe that this is possible with JavaScript in it's current guise. There are ways that could be coded to mimic UI blocking, such as using showModalDialog
or having some global blocking
boolean which are about as near as you can get I'm afraid.
这篇关于Javascript中的睡眠()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!