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.
If someWork() is intensive, you will still hang the browser at each interval.
Possible ways:
It all comes down to your requirements & constraints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With