user2551541
user2551541

Reputation: 1

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

Upvotes: 0

Views: 84

Answers (2)

Jeremy
Jeremy

Reputation: 3538

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

Upvotes: 0

krishnakid
krishnakid

Reputation: 108

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

Upvotes: 2

Related Questions