Javascript clearInterval函数

时间:2013-08-14 10:31:48

标签: javascript jquery oop

我是Javascript或jQuery的OOP新手,我试图清除间隔并停止间隔内的任何方法,它似乎与我在下面所做的不一致。

function Timer() {
    var sec = $('.timer #second');

    this.runTimer = function(_currentime) {
        var currentTimeing = parseInt($(_currentime).text());
        this.timeInterval = setInterval(function() {
            $('.projects li span.second').text(currentTimeing++)
        }, 1000); 

        $("#stop").click(function() {
            // clear interval
            clearInterval(this.timeInterval);
        })
    }
}

var play = new Timer();

$("#start").click(function(){
    //console.log(this.runTimer())
    play.runTimer('#second');
})

2 个答案:

答案 0 :(得分:1)

您在不同功能的上下文中使用this,这就是为什么它不能正常工作。尝试:

 function Timer() {

    var sec = $('.timer #second');

    this.runTimer = function(_currentime) {

      var currentTimeing = parseInt($(_currentime).text()), that = this;
      that.timeInterval = setInterval(function(){
        $('.projects li span.second').text(currentTimeing ++)
      }, 1000); 

      $("#stop").click(function(){
        // clear interval
        clearInterval(that.timeInterval);
      })
    }
  }

  var play = new Timer();

  $("#start").click(function(){
    //console.log(this.runTimer())
    play.runTimer('#second');
  })

我只是在this变量中保存对正确that的引用,以便稍后我可以用它来清除间隔。

答案 1 :(得分:0)

function Timer() {

    var sec = $('.timer #second');
    var timeinterval;   // declare timeinterval variable here
    this.runTimer = function(_currentime) {

      var currentTimeing = parseInt($(_currentime).text());
      timeInterval = setInterval(function(){
        $('.projects li span.second').text(currentTimeing ++)
      }, 1000); 

      $("#stop").click(function(){
        // clear interval
        clearInterval(timeInterval);
      })
    }
  }

  var play = new Timer();

  $("#start").click(function(){
    //console.log(this.runTimer())
    play.runTimer('#second');
  })