在javascript中对表/像素图像进行一些循环时,我试图异步执行,以防止浏览器滞后。
因此,当执行一定数量的迭代时,我试图退出并恢复for
循环。它是x
和y
坐标的嵌套循环。这是我的概念:
//`data` contains info from prewious executions
function asynchronous(data) {
var x = data.x;
var y = data.y;
var max_x = ...;
var max_y = ...;
var iterations = 0;
var max_iterations = 1000;
for(;y<max_y&&iterations<max_iterations; y++) {
for(;x<max_x&&iterations<max_iterations; x++) {
//Do something
...
//Iterate iterations
iterations++;
}
}
//Print the status
console.log(...);
//Save our position for next execution
data.x = x;
data.y = y;
}
然后,我们可以通过某种间隔来调用它,通常是这样的:
var data = {x:0, y:0};
setInterval(function() {asynchronous.apply(data, []);}, 20);
由于某种原因,变量没有正确重置,我得到无限循环:
我上课了:
new ProgressManager(
function() {
//x and y from prewious iterations
var x = this.x;
var y= this.y;
//Canvas related stuff
var array = this.imageData.data;
var width = this.imageData.width;
var height = this.imageData.height;
//step in this progress execution
var step=0;
//Iterate through x and y, starting from prewious values
for (;y < height&&step<1000; y++) {
//Cache computed y offset
var ofy = y * width;
for (;x < width&&step<1000; x++) {
//Do some canvas operation here
//Iterate step
step++;
}
}
this.x = x;
this.y = y;
this.progress+=step;
return new ProgressEvent(null, null, variables.progress/(width*height),1);
},
//Data for the progress
{x:0,y:0,progress:0,ctx:ctx,imageData:data},
//onFinish callback
function() {
console.log("DONE!");
this.ctx.putImageData(this.imageData);
},
//onProgress callback
function(event) {
document.title=Math.round((event.progress)*1000)/10+"%";
}
).start();