AngularJS。执行长时间运行的任务 [英] AngularJS. Executing long-running tasks

查看:92
本文介绍了AngularJS。执行长时间运行的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AngularJS是否有一些执行长时间运行任务的机制?例如,GWT具有如下特性:

Does AngularJS has some mechanism for executing long-running tasks? For example GWT has feature like this:


有时您想要分解逻辑循环,以便JavaScript
事件循环得到有机会在两段代码之间运行。 GWT中的
Scheduler类将允许您这样做。在将控制
返回到JavaScript事件循环之后,
传递给Scheduler的逻辑将在未来的某个时刻运行。这个小延迟可能
为接口提供处理某些用户事件或初始化
其他代码的机会。

Sometimes you want to break up your logic loop so that the JavaScript event loop gets a chance to run between two pieces of code. The Scheduler class in GWT will allow you to do that. The logic that you pass to Scheduler will run at some point in the future, after control has been returned to the JavaScript event loop. This little delay may give the interface a chance to process some user events or initialize other code.


推荐答案

在JavaScript中,您可以通过强制异步执行代码来执行此操作:

In JavaScript you do this by forcing asynchronous execution of code:

setTimeout(function () {
    // ... code executed at some later point in time
}, 0);    // timeout of `0` means it will get executed as soon as possible

在AngularJS中,你' d使用 $ timeout 服务执行此操作,然后在单元测试中轻松模拟。

In AngularJS, you'd do this with the $timeout service, which is then easily mocked in unit-tests.

为了给你一个完整的例子:

To give you a full-fledged example:

var maxIterations = 100000;
(function brokenUpFn (i) {
    if (i >= maxIterations) {
        return;
    }

    do {
        // ... (some computation-intensive code here)
        i++;
    } while (i % 100);

    setTimeout(brokenUpFn, 0, i);
})(0);

这篇关于AngularJS。执行长时间运行的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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