Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you do a for loop on a timer?

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!

like image 257
fancy Avatar asked May 26 '26 19:05

fancy


2 Answers

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();
like image 200
jfriend00 Avatar answered May 30 '26 11:05

jfriend00


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);
like image 26
LandonSchropp Avatar answered May 30 '26 09:05

LandonSchropp