简体   繁体   中英

Looping within functions

I'd like to repeat a certain piece of code with a two second interval inbetween, how would I do so?

$(document).keydown(function(e) {
      kkeys.push( e.keyCode );
      if ( kkeys.toString().indexOf( konami ) >= 0 ) {
        $(document).unbind('keydown',arguments.callee);
            $('.preview').attr('style', 'background: #'+Math.floor(Math.random()*16777215).toString(16) + ';');
      }
    });

with this being repeated:

$('.preview').attr('style', 'background: #'+Math.floor(Math.random()*16777215).toString(16) + ';');

You will probably want to use a conjunction of

setTimeout()

with a recursive call to the function and the proper base case.

you can keep an argument as the total time elapsed and use that to do what you want. You can also use

setInterval()

That should put you on the right track

Simple loops in javascript, jquery not required...

// simple for loop
var array = [1,2,3,4];
for (var i = 0; i < array.length; i++){
    console.log(array[i]);
}

// simple while loop
var i = 0;
while (i < 4){
    console.log(array[i]);
    i++;
}

// simple object iteration
var object = { a:1, b:2, c:3, d:4 };
for (var attribute in object){
    if (object.hasOwnProperty(attribute) === true){
        console.log(object[attribute]);
    }
}

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