有没有正确的“屈服”方法?在javascript中的协作线程意义上?
我正在编写一个普遍存在的插件,ajax 查询的长函数回调阻塞了 GUI 线程,导致 Firefox 锁定。
显而易见的解决方案似乎是使用某种延迟执行(即我们希望定期将 执行此查询 函数添加到事件队列的末尾,然后允许携带其他命令 。
我能想到的唯一方法是使用超时为零的 settimeout ...这是否保证有效,或者是否有更好的方法来做到这一点
I'm writing a ubiquity plugin the long function callback for an ajax query is blocking up the GUI Thread causing firefox to lock up.
The obvious solution seem to be to use some sort of deferred execution of (i.e we want to periodically add the carry out doing this query function to the end of the event queue and then allow other commands to be carried out.
The only way I can think of doing this is to use settimeout with a timeout of zero... is this is guaranteed to work, or is there a better way of doing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
setTimeout
和一个非常小的超时(0
或非常接近零,如果你感觉偏执)是在浏览器上下文中执行此操作的唯一方法。它工作得很好并且非常可靠,但是一定要足够频繁地产生结果,但不要太频繁,因为它确实需要一段时间才能返回给您(计算机意义上的“一段时间”,当然;用人类的术语来说,这几乎是瞬时的(以你可能正在做的其他事情为模数)。Using
setTimeout
with a very small timeout (0
or very nearly zero if you're feeling paranoid) is the only way to do this in a browser context. It works very well and is very reliable, but be sure to yield often enough but not too often, as it does take a while to come back to you ("a while" in a computer sense, of course; it's almost instantaneous [modulo other things you may be doing] in human terms).确保您使用的是异步请求,因为同步请求会阻止浏览器(这将解释 GUI 锁定)。
如果这不是你的问题,我想你想要类似这个任务队列的东西。
调用
runQueue.next()
执行下一个任务。将其包装在 try..catch 语句中,如下所示:Make sure you are using an asynchronous request as a synchronous request blocks the browser (which would explain the GUI lock-up).
If this is not your problem, I think you want something like this task queue.
Call
runQueue.next()
to execute the next task. Wrap it in a try..catch statement as such: