Reputation: 6694
I have a very CPU-intensive JS function that makes browsers kill it because of long no response. I want to have the function finished, and also i want to be able to use my browser in the meanwhile.
My solution was to implement a sleep-alike functionality in my function after each iteration:
<p id="debug"/>
<script>
function example(i) {
//do stuff
if(i < 100) window.setTimeout(function() {example(i+1);}, 100);
}
example(0);
</script>
The solution works well - but is there is any nicer way to implement this functionality? - without using the unnecessary recursion.
Upvotes: 1
Views: 263
Reputation: 6378
var sleep = function(period, decision, callback){
var interval = setInterval(function(){
if (decision()) {
interval = clearInterval(interval);
callback();
}
}, period);
}
Upvotes: 0
Reputation: 3136
There is something called web workers which is similar to Threading. Refer: http://www.html5rocks.com/en/tutorials/workers/basics/
Upvotes: 3