2013-09-23 19 views
6

以下是一個示例情況。在setInterval/setTimeout中使用變量作爲時間

var count, 
    time = 1000; 

setInterval(function(){ 
    count += 1; 
}, time); 

上面的代碼會將「count」var增加1,非常大,爲1000毫秒。 似乎setInterval在觸發時將使用它在執行時看到的時間。 如果稍後更新了該值,則不會考慮這一點,並將在設置的初始時間後繼續觸發。

我該如何動態更改此方法的時間?

+1

http://stackoverflow.com/questions/1280263/changing-the-interval-of-setinterval-而它的運行 – Tomalla

回答

7

使用setTimeout代替回調和變量而不是數字。

function timeout() { 
    setTimeout(function() { 
     count += 1; 
     console.log(count); 
     timeout(); 
    }, time); 
}; 
timeout(); 

演示here

較短的版本是:

function periodicall() { 
    count++; 
    setTimeout(periodicall, time); 
}; 
periodicall(); 
+3

這一個對我來說最有意義:) – Panomosh

+0

@Panomosh,開心我可以幫助:) – Sergio

0

整數在JavaScript中沒有通過引用傳遞,意味着無法通過更改變量來更改間隔。

只需取消setInterval並使用新時間重新啓動它。

例子可以在這裏找到: http://jsfiddle.net/Elak/yUxmw/2/

var Interval; 

(function() { 
    var createInterval = function (callback, time) { 
     return setInterval(callback, time); 
    } 

    Interval = function (callback, time) { 
     this.callback = callback; 
     this.interval = createInterval(callback, time); 
    }; 

    Interval.prototype.updateTimer = function (time) { 
     clearInterval(this.interval); 
     createInterval(this.callback, time); 
    }; 

})(); 

$(document).ready(function() { 
    var inter = new Interval(function() { 
     $("#out").append("<li>" + new Date().toString() + "</li>"); 
    }, 1000); 

    setTimeout(function() { 
     inter.updateTimer(500); 
    }, 2000); 
}); 
2

嘗試:

var count, 
    time = 1000, 
    intId; 
function invoke(){ 

    intId = setInterval(function(){ 
     count += 1; 
     if(...) // now i need to change my time 
     { 
      time = 2000; //some new value 
      intId = window.clearInterval(intId); 
      invoke(); 
     } 
    }, time); 

} 

invoke(); 

,因爲它被設置一次,你不能動態地更改間隔,然後你不重新運行的setInterval代碼。所以你可以做什麼來清除間隔,並再次設置它運行。您也可以使用類似邏輯的setTimeout,但使用setTimeout您需要每次註冊一個超時,並且您不需要使用clearTimeout,除非您想在兩者之間中止。如果你每次都在改變時間,setTimeout更有意義。

var count, 
time = 1000; 

function invoke() { 
    count += 1; 
    time += 1000; //some new value 
    console.log('displ'); 
    window.setTimeout(invoke, time); 
} 
window.setTimeout(invoke, time); 
1

你不能(據我所知)動態改變間隔。我會建議使用回調進行此操作:

var _time = 1000, 
_out, 
_count = 0, 
yourfunc = function() { 
    count++; 
    if (count > 10) { 
     // stop 
     clearTimeout(_out); // optional 
    } 
    else { 
     // your code 
     _time = 1000 + count; // for instance 
     _out = setTimeout(function() { 
      yourfunc(); 
     }, _time); 
    } 
};