2014-04-07 53 views
0

我很難得到一個倒計時器工作,因爲我不知道我做錯了什麼。我試圖在原型中使用jQuery設置倒數計時器。在使用jQuery的原型中設置計時器事件

我看到到目前爲止的主要問題是在的setInterval:

_self.counter = setInterval(_self.runTimer(_self),1000); 

當我沒有在「這個」我得到NaN的通過,但是當我做倒計時只會發生一次,然後停止。

這裏是我的jsfiddle工作至今:

http://jsfiddle.net/f9GN7/

預先感謝您。

+0

'_self.runTimer(_self)'沒有做什麼,你認爲它。它運行一次,並將'undefined'返回給'setInterval'。你想把它傳遞給函數:'setInterval(_self.runTimer,1000)' – blgt

+0

當我這樣做時,它只是發送NaN。 – seroth

回答

1

我已經修改了立你的代碼有點麻煩,我把setInterval改爲setTimeout。

var timer_code = function(){ 
    this.counter; 
    this.timeCountDown = 30; 
} 

timer_code.prototype = { 
    init : function(){ 
     var _self = this; 
     $('#start').on('click',function(e){ 
      _self.setTimer(); 
     }); 
    }, 

    setTimer : function(){ 
     var _self = this; 
     // _self.counter = setInterval(_self.runTimer(_self),1000); 
     var timerLoop = function(){ 
      if(_self.timeCountDown > 0){ 
       _self.runTimer(); 
       setTimeout(timerLoop, 1000); 
      } 
     }; 
     timerLoop(); 
    }, 

    runTimer : function(){ 
     var _self = this; 
     _self.timeCountDown--; 
     if(_self.timeCountDown <= 0){ 
     // clearInterval(_self.counter); 
      $('#timer').html("DONE"); 
      return; 
     } 
     $('#timer').html(_self.timeCountDown); 
     console.log(_self.timeCountDown); 
    } 
} 

var timer = new timer_code(); 
timer.init(); 

http://jsfiddle.net/f9GN7/1/

+0

[爲什麼你應該使用setTimeout而不是setInterval](http://warp.byu.edu/site/content/1117) –

+0

就像一個冠軍。謝謝。 – seroth

0

的setInterval得到一個函數引用作爲第一個參數..

此功能可能無法返回一個函數對象,函數調用你剛過需要被調用的closure

的scoope保持你代碼只需少量的修改:

setTimer: function(){ 
    if(this.counter) 
    clearInterval(this.counter); // timer may have already been launched, it may need to be cleared if its value is an integer and is != 0 
    this.counter = setInterval(
    (function (ref) { 
     return function() { 
      ref.runTimer(); 
     } 
    })(this), 
    1000); 
} 

Fiddle Here

相關問題