dave dave
dave dave

Reputation: 957

javascript: how can I create a slow for...in loop

I'm building my own slideshow. I'd like to iterate over the members of an object, with an observable pause between each iteration.

Using setInterval,I've come up with this:

for (key in ob) {

setInterval(
    function (){
    console.log("Key:", key);
    console.log("Value:", ob[key]);
    }, 2000

        ) 

}

However, this doesn't work. It dumps logs the key/value pairs instantly, where my expectation is that there would be an interval between each operation.

How do I do the iteration with a pause between each operation?

Upvotes: 1

Views: 87

Answers (2)

Bernie
Bernie

Reputation: 5055

Create a self recalling timeout for example:

function slowLoop(){
   setTimeout(function(){
   // Do something

   slowLoop();
   }, 2000);
}

Upvotes: 0

Esailija
Esailija

Reputation: 140228

You can't do it like that at all.

Try this:

var keys = Object.keys(ob);
var index = 0;
setInterval( function(){
    console.log( keys[index], ob[keys[index]] );
    index = ( index + 1 ) % keys.length;
}, 2000 );

http://jsfiddle.net/DgAPw/

An example that doesn't roll around but instead stops once everything has been processed:

var keys = Object.keys(ob);
var index = 0;
var timer = setInterval( function(){
    console.log( keys[index], ob[keys[index]] );
    index++;
    if( index >= keys.length ) {
        clearInterval( timer );
    }
}, 2000 );

Upvotes: 2

Related Questions