我想将JavaScript中使用的for循环转换为异步格式,以便在浏览器中运行时删除不响应错误的脚本。我的代码如下:
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;
}
}
}
答案 0 :(得分:1)
您可以使用计时器,以便内部延迟执行。这是一个例子:
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
});
答案 1 :(得分:0)
您可能希望将工作人员用于后台任务。
了解详情:http://www.w3schools.com/html/html5_webworkers.asp
以下是与您的案例相关的示例:
<!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>