2015-05-25 22 views
5

Così ho questo codicecome smettere di timer con un'altra funzione javascript

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? 
} 

il timer function() inizia come il caricamento della pagina, ma se ho un pulsante per StopTime() e mi clic su di esso, come interrompo la prima funzione dall'esecuzione e la interrompo dal colpire il segno di 3000 millisecondi e avvisando "Fuori dal tempo"?

+0

È necessario assegnare un nome al timer a una var globale – colecmc

risposta

6

Utilizzare una variabile con ambito su tutte le funzioni.

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? 
} 

provare questo si lavorerà per voi

+1

ciò che è 'clearTimer'? – colecmc

+0

@colecmc scusa il mio errore –

-1

Il valore restituito da setTimeout è un ID univoco che è possibile utilizzare in seguito per annullare il timeout con clearTimeout.

var timeout; 

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

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

function stopTime() { 
    clearTimeout(timeout); 
}