Reputation: 20571
Does AngularJS has some mechanism for executing long-running tasks? For example GWT has feature like this:
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.
Upvotes: 0
Views: 2166
Reputation: 3938
JavaScript historically suffers from an important limitation: all its execution process remains inside a unique thread.
You can try simulate parallel tasks using setTimeout()
and setInterval()
methods. HTTP requests can also be done in an asynchronous manner, thanks to the XMLHttpRequest
object that avoids freezing the UI while loading resources from remote servers.
The Web Workers APIs define a way to run script in the background. You can then execute some tasks in threads living outside the main page.
Take a look at this article and this example Be aware that only new browsers support this feature
Upvotes: 1
Reputation: 7214
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
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);
Upvotes: 2