2015-05-25 90 views
5

Yani bu kodunasıl)

function timer() 
{ 
    setTimeout(function(){alert("Out of time")}, 3000); //Alerts "Out of time" after 3000 milliseconds 
} 
function resetTime() 
{ 
    timer(); //this is not right, i thought it would override the first function but it just adds another timer as well which is not what I want 
} 
function stopTime() 
{ 
    //What could go here to stop the first function from fully executing before it hits 3000 milliseconds and displays the alert message? 
} 

fonksiyon zamanlayıcı (varsa javascript başka fonksiyonu ile Sayacı durdurmak sayfa yüklenirken başlar ama StopTime için bir düğme var() ve eğer bunu tıklayın, nasıl İlk fonksiyonu 3000 milisaniye isabetinden ve "Zaman doldu" uyarısını yapmaktan durdurup durdurabilir miyim?

+0

Zamanlayıcıyı global bir varlığa adlandırmanız gerekir – colecmc

cevap

6

Tüm işlevlerinizin üzerinde bir değişken içeren bir değişken kullanın.

var myTimer; 
... 
myTimer = setTimeout(...); 
... 
clearTimeout(myTimer); 
1
var timer; 

function timer() 
{ 
    timer = setTimeout(function(){alert("Out of time")}, 3000); //Alerts "Out of time" after 3000 milliseconds 
} 
function resetTime() 
{ 
    clearTimeout(timer); 
    timer(); //this is not right, i thought it would override the first function but it just adds another timer as well which is not what I want 
} 
function stopTime() 
{ 
    //What could go here to stop the first function from fully executing before it hits 3000 milliseconds and displays the alert message? 
} 

değerin setTimeout döndü

+1

'clearTimer' nedir? – colecmc

+0

@colecmc üzgünüm hatam –

-1

Eğer clearTimeout ile zaman aşımı iptal etmek için daha sonra kullanabilirsiniz benzersiz bir kimliktir için bu Çalışacak bu deneyin.

var timeout; 

function timer() { 
    timeout = setTimeout(/* ... */); 
} 

function resetTime() { 
    stopTime(); 
    timer(); 
} 

function stopTime() { 
    clearTimeout(timeout); 
}