2017-02-09 2 views
0

У меня есть функция, которая отображает отсчетные часы в соответствии с переменной. Каким будет правильный способ остановить его в указанном состоянии? clearTimeout не останавливает функции Decrement.остановка функции обратного отсчета javascript, если условие

function interface_vip(type){ 
    var timeout = ''; 
    var clock = ''; 
    //display clock 
    function Decrement() { 
     currentMinutes = Math.floor(secs/60); 
     currentSeconds = secs % 60; 
     if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds; 
      secs--; 
      if(secs !== -1) timeout = setTimeout(Decrement,1000); 
    } 
    if (type == 1){ 
     var mins = 20; 
     var secs = mins * 60; 
     var currentSeconds = 0; 
     var currentMinutes = 0; 
     clock = setTimeout(Decrement,1000); 
    } 
    if (type == 2){ 
     clearTimeout(clock); 
     clearTimeout(timeout); 
    } 
} 
+0

У вас есть ошибка, t не определена –

+1

l ook, что 'interface' является зарезервированным словом в JavaScript https://mathiasbynens.be/notes/reserved-keywords#ecmascript-2 –

+0

переменная t определена в my js, я изменю ее на число в моем вопросе, это рабочий – Adry

ответ

2

Ваши часы идентификатор теряется при втором вызове, плохое решением является создание переменного глобального

var timeout = ''; 
     var clock = ''; 
    function interface_vip(type){ 
     //display clock 
     function Decrement() { 
      currentMinutes = Math.floor(secs/60); 
      currentSeconds = secs % 60; 
      if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds; 
       secs--; 
       if(secs !== -1) timeout = setTimeout(Decrement,1000); 
     } 
     if (type == 1){ 
      var mins = 20; 
      var secs = mins * 60; 
      var currentSeconds = 0; 
      var currentMinutes = 0; 
      clock = setTimeout(Decrement,1000); 
     } 
     if (type == 2){ 
      clearTimeout(clock); 
      clearTimeout(timeout); 
     } 
    } 

лучшего подходом в сильфоне сниппета

function interface_vip(){ 
 
    var timeout = ''; 
 
    var t = 0; 
 
    var clock = ''; 
 
    //display clock 
 
    function Decrement() { 
 
     currentMinutes = Math.floor(secs/60); 
 
     currentSeconds = secs % 60; 
 
     if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds; 
 
      secs--; 
 
      if(secs !== -1) timeout = setTimeout(Decrement,1000); 
 
    } 
 
    this.start = function(){ 
 
     var mins = t; 
 
     var secs = mins * 60; 
 
     var currentSeconds = 0; 
 
     var currentMinutes = 0; 
 
     clock = setTimeout(Decrement,1000); 
 
    } 
 
    this.stop = function(){ 
 
     clearTimeout(clock); 
 
     clearTimeout(timeout); 
 
    } 
 
} 
 
var interf = new interface_vip(); 
 
interf.start(); 
 
interf.stop();

+0

Спасибо! Я не мог этого видеть. Это решает проблему: D – Adry

+0

Я добавил лучшее решение в ответ –

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