在javascript中运行长时间的操作? [英] Running a long operation in javascript?

查看:168
本文介绍了在javascript中运行长时间的操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种在javascript中执行长时间运行操作的好方法?例如,我有一个可能需要2分钟才能运行的功能。我们如何打破像这样的大型行动?如果我使用的是java或C,我会在后台线程中执行此任务。有没有办法告诉浏览器暂停脚本的执行,以便它可以让它的前台/ UI线程再次工作?这样的东西?:

Is there a good way of performing a long-running operation in javascript? For example, I have a function which may take 2 minutes to run. How do we break up a large operation like this? If I was using java or C, I would perform this task in a background thread. Is there a way to tell the browser to pause execution of the script so it can let its foreground/UI thread work again? Something like this?:

function bigJob() {
    for (i = 0; i < 1000000; i++) {
        someWork();
        sleep(1000);
    }
}

谢谢

推荐答案

如果你想让它睡觉,你可以在一个间隔内运行它:

If you want it to sleep, you would run it in an interval:

var i = 0;    
var jobInterval = setInterval(bigJob, 1000);

function bigJob() {
      somework();

      i++;
      if(i>1000000) {
            clearInterval(jobInterval);
      }
}

您必须跟踪迭代次数函数,并在完成时终止间隔。

You would have to track the number of iterations in the function, and kill the interval when you are done.

如果someWork()是密集的,你仍然会在每个时间间隔挂起浏览器。

If someWork() is intensive, you will still hang the browser at each interval.

这篇关于在javascript中运行长时间的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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