简体   繁体   English

在函数内循环

[英]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... javascript中的简单循环,不需要jquery ......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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