2015-12-01 142 views
0
setInterval(function hello() { 
    console.log('hello world'); 
    return hello; 
}(), 6000); 

我怎麼可以清除的時間間隔,我想補充的VAR間隔清除設置的時間間隔

var i =0; 
var interval = setInterval(function hello() { 
    console.log('world'); 
    if(++i == 3) clearInterval(interval); 
    return hello; 
}(), 5000); 

但它並沒有奏效。謝謝你的幫助。

+1

'clearInterval()'肯定能行。是什麼讓你覺得它沒有? – Pointy

+0

爲什麼你只嘗試在每次迭代中清除間隔? –

+0

定義「* ...它沒有工作*」。你期望什麼?究竟發生了什麼?你有沒有收到任何錯誤訊息? – RobG

回答

2

clearInterval()肯定有效。你有錯誤在下面的代碼行:

}(), 5000); 
    //^^ remove() as this is not IIFE 
+0

爲什麼downvoted ??我錯了嗎? –

0
var i =0; 
var interval = setInterval(function hello() { 
    console.log('world'); 
    if(++i == 3) clearInterval(interval); 
    return hello; 
}(), 5000); // notice those parenthesis 

你應該處理程序傳遞給setInterval()不到位調用它,