What's the best way to do something like this?
for a in b
#do this thing
#wait a second, then continue the loop
in js
var a, _i, _len;
for (_i = 0, _len = b.length; _i < _len; _i++) {
a = b[_i];
//do this thing
//wait a second, then continue the loop
}
Thanks!
To process one item from a for (i in b) loop each second until you're done with the items, you can do it like this:
var list = [];
// accumulate list of items to operate on into an array
// that can be incremented through
for (var i in b) {
list.push(i);
}
function next() {
if (list.length > 0) {
var item = list.shift();
// do something with the next item here
// do the next iteration one second later
setTimeout(next, 1000);
}
}
// start it
next();
I think this would work with JavaScript:
var b = [1, 2, 3];
var timer;
var i = 0;
function timerFunction() {
// base case
if (i >= b.length) {
clearInterval(timer);
return;
}
var element = b[i];
// do stuff to b here
i++;
}
// if you want to execute it right away
timerFunction();
// start the timer
timer = setInterval(timerFunction, 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With