Reputation: 1
I want to convert a for-loop used in JavaScript to asynchronous format in order to remove the script not responding error while running in browsers. My code is given below:
links.Timeline.prototype.stackItemsCheckOverlap = function(items, itemIndex,
itemStart, itemEnd) {
var eventMargin = this.options.eventMargin,
collision = this.collision;
var item1 = items[itemIndex];
//for loop that I want to change as asynchronous
for (var i = itemEnd; i >= itemStart; i--) {
var item2 = items[i];
if (collision(item1, item2, eventMargin)) {
if (i != itemIndex) {
return item2;
}
}
}
Upvotes: 0
Views: 297
Reputation: 119877
You can use a timer so that it internally defers executions. Here's an example:
function asyncLoop(array, callback){
var i = 0;
var timer = setInterval(function(){
callback.call(array, array[i]);
if(++i === array.length) clearInterval(timer);
}, 0);
}
asyncLoop([1,2,3], function(item){
// this will run per item but will not block execution
});
Upvotes: 1
Reputation: 696
Possible duplication: JavaScript and Threads
You would want to use a worker for background tasks.
Read more: http://www.w3schools.com/html/html5_webworkers.asp
Here's an example that is related to your case:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script id="worker1" type="javascript/worker">
self.onmessage = function(e) {
// Whatever you want to run in background, for example
for (var i = 0; i < 100; i++) {
console.log(i);
}
self.postMessage(0); // Post back a message, to close the worker
}
</script>
<script>
function run_task() {
if (typeof(Worker) != "undefined") {
// Here I am using a blob so I can run worker without using a separate file. It works on Chrome, but may not work on other browsers
var blob = new Blob([document.querySelector('#worker1').textContent], { type: "text/javascript" });
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
worker.terminate(); // Close the worker when receiving the postback message
}
worker.postMessage(1); // Start the worker. You can also use this function to pass arguments to the worker script.
} else {
// You browser does not support Worker
}
}
run_task(); // Run the function. You probably want to trigger this somewhere else
</script>
</body>
</html>
References: https://stackoverflow.com/a/6454685/2050220
Upvotes: 0