clearTimeout при динамическом обновлении таймера - PullRequest
1 голос
/ 10 марта 2012

У меня есть таймер, который я обновляю динамически.

------------------ обновление -------------------------- Когда я впервые опубликовал вопрос, я не думал, что имеет значение, что таймер вызывается из представления магистрали, но я считаю, что в результате этого я не могу использовать глобальную переменную (или, по крайней мере, глобальную переменную). не работает). Я буду вызывать несколько таймеров, поэтому установка только одной глобальной переменной и ее удаление не будут работать. Я должен быть в состоянии очистить один таймер без очистки других.

Что я запускаю таймер,

 
function countDown(end_time, divid){
    var tdiv = document.getElementById(divid),
        to;
    this.rewriteCounter = function(){


      if (end_time >= MyApp.start_time)
      {


        tdiv.innerHTML =  Math.round(end_time - MyApp.start_time);
      }
      else {
        alert('times up');
      }
    };
    this.rewriteCounter();
    to = setInterval(this.rewriteCounter,1000);
}

в моем приложении я запускаю таймер в режиме магистрали с помощью

MyApp.Views.Timer = Backbone.View.extend({
 el: 'div#timer',

 initialize: function(){
     timer = this.model;
     this.render();
 },
 events: {
    "clicked div#add_time": "update_timer"
 }

 render: function(){
    $(this.el).append(HandlebarsTemplates['timer'](timer);
    this.start_timer();
 },
 start_timer: function(){
    delete main_timer; // this doesn't work :(
    clearTimtout(main_timer); //this doesn't work either :(

    var main_timer = setTimeout(new countDown(timed.length, 'main_timer'),timed.length*1000);
 },

 update_timer: function(){
   timed.length=timed.length+30
  this.start_timer();
 }
});

так что я пытаюсь обновить таймер, убить старый таймер и перезапустить его с новыми значениями. У меня есть разные таймеры, поэтому простой вызов timed.length в функции обратного отсчета не сработает.

1 Ответ

2 голосов
/ 10 марта 2012
var main_timer = setTimeout(new countDown(timed.length, 'main_timer'),timed_length*1000);

Этот оператор создает локальную переменную main_timer. Вместо этого вы должны создать глобальную переменную и использовать ее для очистки времени ожидания, как показано ниже

clearTimtout(main_timer);
main_timer = setTimeout(new countDown(timed.length, 'main_timer'),timed_length*1000);

EDIT:

использовать функцию в качестве обработчика setTimeout, как показано ниже

clearTimeout(main_timer); 
main_timer = setTimeout(function(){
    new countDown(timed.length, 'main_timer');
},timed_length*1000);

примечание: надежда timed.length и timed_length верны.

EDIT:

изменить countdown, как указано ниже.

function countDown(end_time, divid){
    var tdiv = document.getElementById(divid),
        to;
    this.rewriteCounter = function(){


      if (end_time >= MyApp.start_time)
      {


        tdiv.innerHTML =  Math.round(end_time - MyApp.start_time);
      }
      else {
        alert('times up');
      }
    };

    this.clearRewriteCounter = function(){
      clearInterval(to);
    }

    this.rewriteCounter();
    to = setInterval(this.rewriteCounter,1000);

    return this;
}

и в MyApp.Views.Timer

MyApp.Views.Timer = Backbone.View.extend({
 el: 'div#timer',

 initialize: function(){
     timer = this.model;
     this.render();
 },
 events: {
    "clicked div#add_time": "update_timer"
 }

 render: function(){
    $(this.el).append(HandlebarsTemplates['timer'](timer);
    this.start_timer();
 },
 start_timer: function(){
    clearTimeout(this.main_timer); 
    this.main_timer = setTimeout(function(){
        if(this.countDownInstance){
            this.countDownInstance.clearRewriteCounter();
        }
        this.countDownInstance = new countDown(timed.length, 'main_timer');
    },timed_length*1000);
 },

 update_timer: function(){
   timed.length=timed.length+30
  this.start_timer();
 }
});
...