简体   繁体   中英

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?

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 );

Create a self recalling timeout for example:

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

   slowLoop();
   }, 2000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM