2016-11-24 110 views
-3

我試過設定的時間間隔,以便函數computercardArrange()應該在2秒後調用一次。但是它在2秒後多次調用函數computercardArrange()。我如何停止,以便函數computercardArrange()僅在2秒後被調用一次。以下是代碼。在2秒後停止setInterval()

function timer() { 
setInterval(function(){ 

    computercardArrange(); // This function should be called only one time after 2 second. 


    }, 2000); 
} 
+1

您應該使用函數setTimeout代替。 – Dekel

+1

你有沒有試過setTimeout? –

回答

5

只需使用setTimeout代替

function timer() { 
setTimeout(function(){ 
    computercardArrange(); // This function should be called only one time after 2 second. 
    }, 2000); 
} 

如果我想調用該函數的10倍和停止 間隔?

var callCount = 0 ;  

function timer() { 
var intervalIdentifier = setInterval(function(){ 
    computercardArrange(); 

    if (++ callCount == 10) { 
     clearInterval(intervalIdentifier); 
    } 

    }, 2000); 
} 
+0

如果我想調用該函數10次並停止間隔,該怎麼辦? –