簡體   English   中英

使用javascript的setTimeout多次運行匿名函數

[英]Run a anonymous function several times using javascript's setTimeout

我在網站上使用以下功能。 借用我正在使用的草率的jQuery,有什么方法可以多次運行此函數,而無需將其聲明為獨立函數,也無需多次復制和粘貼代碼?

展覽A:

setTimeout(function(){

    $('.nav > li > a').each(function(k,el){
        var width = $(this).parent().width();
        $(this).next('span').width(width);
    });

},1000);

我不想這樣做:

setTimeout(function(){
        // same code here   
},1000);

setTimeout(function(){
        // same code here   
},3000);

setTimeout(function(){
        // same code here   
},5000);

我也不想這樣做:

function myfunction{
    // same code here   
}

setTimeout('myFunction()',1000);
setTimeout('myFunction()',3000);
setTimeout('myFunction()',5000);

是的,請使用setInterval方法。

setInterval(function() {
    $('.nav > li > a').each(function(k,el){
      var width = $(this).parent().width();
      $(this).next('span').width(width);
    }); 
}, 2000);

//run every two seconds

或者,您可以重復調用setTimeout ...

myFun = function() {
    $('.nav > li > a').each(function(k,el){
      var width = $(this).parent().width();
      $(this).next('span').width(width);
    });
    setTimeout(myFun, 2000);
}

setTimeout(myFun,1000);

這應該與執行1000,3000等具有相同的效果...

for (var i = 1000; i <= 5000; i += 2000) {
    setTimeout(func, i);
}

要么

var times = [1000, 3000, 5000];
for (var i=0; i<times.length; i++) {
    setTimeout(func, times[i]);
}

僅限較新的瀏覽器

[1000, 3000, 5000].forEach(function(time){
    setTimeout(func, time);
});

您可以使用$ .map

$.map([1000,3000,5000], function(time,index){ 

 setTimeout(function(){
        $('.nav > li > a').each(function(k,el){
        var width = $(this).parent().width();
        $(this).next('span').width(width);
    });
 },time);

}); 
(function(){
    var i, weirdProblem = function(timeout) {
        setTimeout(function() {
            $('.nav > li > a').each(function(){
                var width = $(this).parent().width();
                $(this).next('span').width(width);
            });
        },timeout);
    };
    for(i = 1; i <= 5; i+=2) {
        weirdProblem(i*1000);
    }
})();

該閉包封裝了聲明,一旦不再使用將被垃圾回收。 雖然不確定這一點。 很奇怪。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM