2015-05-25 2 views
5

Так у меня есть этот кодкак остановить таймер с другой функцией 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? 
} 

функция таймера() начинается при загрузке страницы, но если у меня есть кнопка для останова,() и я нажимаю на него, как остановить выполнение первой функции и остановить ее от попадания отметки в 3000 миллисекунд и предупредить «вне времени»?

+0

Вам нужно указать свой таймер на глобальный var – colecmc

ответ

6

Используйте переменную с областью действия над всеми вашими функциями.

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

попробовать это будет работать для вас

+1

Что такое 'clearTimer'? – colecmc

+0

@colecmc извините, моя ошибка –

-1

Значения, возвращенные из setTimeout является уникальным идентификатором, который можно использовать позже, чтобы отменить тайм-аут с clearTimeout.

var timeout; 

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

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

function stopTime() { 
    clearTimeout(timeout); 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^