1
我試圖在用「new」運算符創建的js對象內使用「setInterval」和「clearInterval」函數。在多個JavaScript對象中調用setInterval和clearInterval函數
HTML:
<button onclick="testList.push(new Test());">run</button>
JS:
Test = function(){
this.y = 0;
this.dy = 10;
that = this;
this.interval = setInterval(function(){
that.y += that.dy;
if (that.y>300){
console.log(that.y); //prints y in console
clearInterval(that.interval);
}
}, 10);
}
當我點擊 「運行」 按鈕,一旦這個工程,我期望的那樣。但是當我在前一個時間間隔沒有被清除(多次快速點擊按鈕)之前多次單擊「運行」按鈕時,間隔不會被清除,並且y會無限遞增。我在這裏犯的錯誤是什麼?
預先感謝您...
想知道爲什麼你使用函數表達式來創建構造函數而不是函數聲明。 – RobG 2014-11-01 12:22:45
@Robg在這裏使用函數表達式的任何缺點(除了該函數在執行該行之前未定義)? – 2014-11-01 12:35:47
就是這樣,這裏寫了很多:[* var functionName = function(){} vs function functionName(){} *](http://stackoverflow.com/questions/336859/var-functionname-function- VS-函數functionname)。我更喜歡在表達式上看到聲明,其中表達式僅用於賦值。但其他人更喜歡在任何地方使用表情,所以一切都是一項任務馬的課程... ;-) – RobG 2014-11-03 02:45:24