i have a javascript array like this:
array = [
{"Command": "SetDuration","QuestionId": "2","NewDuration": "1"},
{"Command": "SetDuration","QuestionId": "2","NewDuration": "1"},
{"Command": "SetDuration","QuestionId": "7","NewDuration": "7"},
{"Command": "SetDuration","QuestionId": "6","NewDuration": "7"}
]
my task is loop through it 1 time in a minute, starting at increm开发者_如何学JAVAented index each time, so that after 3 minutes i would start from array[4] How to accomplish this? Thanks!
The magic of closures:
function createDwindlingLooper(arr) {
var n = 0;
return function() {
for (var i = n; i < arr.length; i++) {
console.log(i); // do real stuff here
}
n += 1;
}
}
var looper = createDwindlingLooper(array);
You can meet your timer requirement with this:
setInterval(createDwindlingLooper(array), 1000 * 60);
The value of n
will be incremented by one each time looper
is executed, achieving the desired effect:
var looper = createDwindlingLooper(array);
looper(); // 0, 1, 2, 3
looper(); // 1, 2, 3
looper(); // 2, 3
looper(); // 3
looper(); //
When you set up your timer, you can do it from inside another function, and that function can maintain the index as a local variable.
function loopVerySlowly(array) {
var index = 0;
function doSomething() {
//
// do something with array[index] ...
//
index = (index + 1) % array.length; // increment for next time
}
return setInterval(doSomething, 1000 * 60);
}
var interval = loopVerySlowly(array);
That depends on how you want to performm the iteration. one way would be to call settimeout four times to run on different indices at minute increments, e.g.
for (var i=0 ; i<4 ; i++)
settimeout(function(i){ return function(){
// process here using i as index
}, 60000*i);
var checkme = {
init: function(start) {
for (var i = start; i < array.length; i++) {
// alert(array[i].Command + ":" + array[i].QuestionId);
//do what you want here
};
// start a new loop from current end
if (array.length < start) {
var t = setTimeout(checkme.init(start+1), 60000);//delay one minute
};
}
};
var t = setTimeout(checkme.init(0), 60000);//start first one in 1 minute
For a BIT more fun, use your "NewDuration" on the current (first) array element in each record so you can vary the amount of time delay by the data :)
NOT what you asked for exactly, but why not!
var checkme = {
init: function(start) {
for (var i = start; i < array.length; i++) {
// alert(array[i].Command + ":" + array[i].QuestionId);
//do what you want here
};
// start a new loop from current end
var timedelay = array[start].NewDuration * 60000;
// delay by NewDuration # minutes
if (array.length < start) {
var t = setTimeout(checkme.init(start+1), timedelay);
};
}
};
var t = setTimeout(checkme.init(0), 60000);//start first one in 1 minute
精彩评论