2016-03-22 3 views
0

, когда пользователь нажимает элемент, он должен инициировать таймаут и установить время начала в true. Затем, если пользователь снова нажимает элемент, когда таймер активен, он должен очистить тайм-аут и возобновить таймаут. Однако я все равно получаю консоль от первого и следующего таймаута. Должно ли cleartimeout оставить меня только с одним, последнее создано? Ive уже попробовал пример из этого вопроса здесь How to reset timeout in Javascript/jQuery?.сброс таймаута javascript

toggleCard: function(card){ 
       var Timer = null; 
       if(this.startTime){ 
        console.log('already activated'); 
        window.clearTimeout(Timer); 
        this.startTime = false; 
       } 

       this.startTime = true; 
       var Timer = setTimeout(function(){ 
//      this.taskCard = false; 
//      this.classCard = true; 
        console.log('old timer') 
       }.bind(this), 5000); 

ответ

1

определяют глобальную переменную, например.

var myTimeOut = 0; 

затем внутри вызова метода clearTimeout

toggleCard: function(card){ 
       clearTimeout(myTimeOut); 
       this.startTime = true; 
       myTimeOut = setTimeout(function(){ 
//      this.taskCard = false; 
//      this.classCard = true; 
        console.log('old timer') 
       }.bind(this), 5000); 
0

Каждый раз, когда функция вызывается, вы создаете новый переменный таймер, поэтому при попытке очистить таймаут, таймер переменный не ссылаются на фактическое время ожидания вы создали.

1

Делай так:

toggleCard: function(card) { 
    window.Timer = null; // <-----------declare timer globally here 
    if (this.startTime) { 
     console.log('already activated'); 
     window.clearTimeout(Timer); // <------- clear here if it is. 
     this.startTime = false; 
    } 

    Timer = setTimeout(function() { // <-------assign the setTimeout here 
     this.startTime = true; // <---------It has to be here. 
     // this.taskCard = false; 
     // this.classCard = true; 
     console.log('old timer') 
    }.bind(this), 5000); 
1

Я думаю, что этот код должен соответствовать вашим требованиям.

var timer = null; 
    var started = false; 
    toggleCard = function (card) { 
     if (started) { 
      console.log('Timer already active'); 
      window.clearTimeout(timer); 
     } else { 
      console.log('Timer active now'); 
      started = true; 
     } 

     timer = setTimeout(function() { 
      console.log('Timer elapsed! '); 
      started = false; 
     }.bind(this), 2000); 
    }; 
Смежные вопросы