2013-02-02 77 views
1

可能重複:
setInterval only runs once?SetInterval只調用一次,不知道爲什麼?

在我開始讓我說作爲一個設計師的邏輯來難,所以我很感謝你我的無知軸承。

我正在製作一個簡單的滑塊,並且我希望它能夠在用戶使用鼠標移動圖片時,程序可以記錄mouseup()之前最後一秒覆蓋的距離,這樣我就可以可以計算出圖片必須經過的模擬效果,就好像它被刷過一樣。

我有我的基本事件處理程序是這樣:

$('.testdiv').mousedown(function(){ 

    pretestFunction(); 

    //mouse is pressed 
    mousepressed = 1; 

    //set first X point 
    prevX = event.pageX; 


}).mouseup(function(){ 

    //get stop X point 
    stopX = event.pageX; 
    mousepressed = 0; 

}); 

pretestFunction調用setInterval的,就像這樣:

function pretestFunction(){ 
    window.setInterval(testFunction(), 1000); 
} 

testfunction():

function testFunction(){ 
    console.log('1 second'); 
} 

我的問題是設置的間隔函數只被調用一次,而不是每秒一次,就像我試圖去做的那樣。我究竟做錯了什麼?

+0

你可以做小提琴嗎? – Mooseman

回答

5
window.setInterval(testFunction(), 1000); 

應該

window.setInterval(testFunction, 1000); 

在第一,要傳遞的價值調用testFunction的(這恰好是undefined,但那並不重要)

在第二個你將通過testFunction的值(即一個函數,這是你想要的。)

+1

啊哈!一個小而昂貴的錯誤。謝謝。在旁註中,我如何將變量傳遞給使用setInterval調用的函數? – styke

+3

如果你有一個函數foo需要一個整數參數,你可以這樣做:setInterval(function(){foo(42);},1000);即傳遞一個匿名函數,用你想要的值調用你的函數。 –

+0

非常感謝。 – styke

相關問題