2015-07-13 4 views
0

У меня есть setInterval по функции X, которая работает каждые 500 мс. В этой функции X я вызываю другую функцию Y, которая по существу связывает событие на некотором div с. Тем не менее, я хотел бы отпереть эти события в следующий раз, когда вызывается функция X (чтобы начать «свежий»). Мой код не похоже на работу:Очистка setInterval() Проблема

setInterval(this.board.updateBoard, 500); //called from another constructor 

Это инициирует функции ниже:

Board.prototype.updateBoard = function() { 
    //I attempt to unbind ALL my divs 
    var divs = this.$el.find("div"); 
    for(var i = 0; i < divs.length; i++) { 
     $(divs[i]).unbind(); //Apparently this doesn't work? 
    } 

    //...some code here... 
    //find appropriate $div's (multiple of them), and then calls this.beginWalking() below on each of those 
    //loop here 
    this.beginWalking($div, direction + "0", direction + "1"); 
    //end of loop 
} 

//alternate between classes to give appearance of walking 
Board.prototype.beginWalking = function ($div, dir0, dir1) { 
    return setInterval(function() { 
     if ($div.hasClass(dir0)) { 
      $div.removeClass(dir0); 
      $div.addClass(dir1); 
     } else { 
      $div.removeClass(dir1); 
      $div.addClass(dir0);    
     } 
    }.bind(this), 80); 
}; 

В основном updateBoard вызывается каждые 500 мс. Каждый раз, когда он вызывается, beginWalking вызывается для установки другого интервала на div. Цель этого другого интервала, который функционирует правильно, заключается в добавлении и удалении класса каждые 80 мс. Я просто не могу отменить все до следующего updateBoard.

Любые предложения оценены!

+0

Кажется, вы связываете события самой платы класса, а не дивы. – Confuseh

+1

Где ваш код для привязки событий? 'function() {} .bind (this)' не является тем же самым связыванием, что и '$ (" selector "). bind()'. Вы хотите очиститьInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval) – coderfin

+0

Вы абсолютно правы. Я сделал большую ошибку, чтобы провести различие между ними. Извини за это!!! – fibono

ответ

2

использование clearInterval() редактирования: $(selector).toggleClass(dir0) также может быть полезным

// In other file, use a global (no var) if you need to read it from another file: 
updaterGlobal = setInterval(this.board.updateBoard, 500); 

// store interval references for clearing: 
var updaterLocals = []; 
Board.prototype.updateBoard = function() { 
    //I attempt to unbind ALL my divs 
    var divs = this.$el.find("div"); 
    // Stop existing div timers: 
    while(updaterLocals.length > 0){ 
     clearInterval(updaterLocals[0]); 
     updaterLocals.shift(); // remove the first timer 
    } 

    //...some code here... 
    //loop here to call the below on several $div's 
    this.beginWalking($div, direction + "0", direction + "1"); 
    //end of loop 
} 

//alternate between classes to give appearance of walking 
Board.prototype.beginWalking = function ($div, dir0, dir1) { 
    var interval = setInterval(function() { 
     if ($div.hasClass(dir0)) { 
      $div.removeClass(dir0); 
      $div.addClass(dir1); 
     } else { 
      $div.removeClass(dir1); 
      $div.addClass(dir0);    
     } 
    }.bind(this), 80); 
    // Save the timer: 
    updaterLocals.push(interval); 
    return; 
}; 
Смежные вопросы