有没有正确的“屈服”方法?在javascript中的协作线程意义上?

发布于 2024-08-05 10:49:12 字数 212 浏览 4 评论 0原文

我正在编写一个普遍存在的插件,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青巷忧颜 2024-08-12 10:49:12

使用 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).

洛阳烟雨空心柳 2024-08-12 10:49:12

确保您使用的是异步请求,因为同步请求会阻止浏览器(这将解释 GUI 锁定)。

如果这不是你的问题,我想你想要类似这个任务队列的东西。

var queue = [];

queue.push(someTaskFunction);
queue.push(anotherTaskFunction);
// ...

var runQueue = (function () {
    var len = queue.length, task = 0;
    for (; task < len; task++) {
        yield queue[task]();
    }
}());

调用runQueue.next()执行下一个任务。将其包装在 try..catch 语句中,如下所示:

try {
    runQueue.next();
} catch (e if (e instanceof StopIteration)) {}

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.

var queue = [];

queue.push(someTaskFunction);
queue.push(anotherTaskFunction);
// ...

var runQueue = (function () {
    var len = queue.length, task = 0;
    for (; task < len; task++) {
        yield queue[task]();
    }
}());

Call runQueue.next() to execute the next task. Wrap it in a try..catch statement as such:

try {
    runQueue.next();
} catch (e if (e instanceof StopIteration)) {}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文