如何在揭示模块模式中使用 clearInterval()

How to Use clearInterval() Within Revealing Module Pattern

我正在编写一个计时器函数,该函数在显示模块模式中使用 setInterval。我可以让计时器正常启动,但我无法停止间隔。

var timer = (function() {
    var startTimer = function() {
        setInterval(function() {
            // Do Stuff
        }, 1000);
    };

    var stopTimer = function() {
        clearInterval(timer.startTimer());
    };

    return {
        startTimer: startTimer,
        stopTimer: stopTimer
    };
})();

timer.startTimer(); // Works!
timer.stopTimer(); // Doesn't Work!

有什么想法吗?

var timer = (function() {

  var timerRef = null;
  var startTimer = function() {
      timerRef = setInterval(function() {
          // Do Stuff
      }, 1000);
  };

  var stopTimer = function() {
      clearInterval(timerRef);
  };

  return {
      startTimer: startTimer,
      stopTimer: stopTimer
  };

})();

试试这个:

var timer = (function() {
    var intervalId;

    var startTimer = function() {
        intervalId = setInterval(function() {
            // Do Stuff
        }, 1000);
    };

    var stopTimer = function() {
        clearInterval(intervalId);
    };

    return {
        startTimer: startTimer,
        stopTimer: stopTimer
    };
})();