停止没有全局变量的setInterval()

时间:2017-07-07 03:24:17

标签: javascript

我希望稍后停止setInterval,我遇到的所有示例都使用全局变量执行此操作,但如果可以的话,我宁愿不使用。

我有一个按钮来启动setInterval而另一个按钮来停止它。我可以很好地开始它,但是如果不使用全局变量我就无法阻止它。

这就是我所拥有的:

function counter() {
  function stop() {
    clearInterval(timer);
  }
  var timer = setInterval(function() {
    console.log(new Date());
  }, 1000);
  return stop;
}
$('#start').click(function() {
  counter();
});
$('#stop').click(function() {
  stop(); // this of course doesn't work
});

3 个答案:

答案 0 :(得分:1)

我认为你需要一个静态变量。但不幸的是,javascript并不支持静态变量。但是,我们可以创建一个。因为在javascript中函数被解释为对象所以它们可以具有静态范围变量。



function counter() {
    if (typeof counter.timer == 'undefined') {
        counter.timer = 0;
    }
    counter.timer = setInterval(function() {
        $("#output").text(new Date());
    }, 1000);
}

function stop() {
    clearInterval(counter.timer);
}
$("#start").on('click', function() {
    counter();
});
$("#stop").on('click', function() {
    stop();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="start">start</button>
	<button type="button" id="stop">stop</button>
  <p id="output"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你需要一个全局变量,但是你可以通过多种方式实现它,所以这里有一个方法,HTML部分:

<button id="start">Start</button>
<button id="stop">Stop</button>

和JS部分:

function timer() {
    var timer = null;
    function stop() {
    clearTimeout(timer);
  }

  function start() {
    timer  = setInterval(function(){
      console.log("repeat it");
    }, 500);    
  }

  return {
      stop,
    start
  };
}

var t = timer();

var startBtn = document.getElementById("start");
var stopBtn = document.getElementById("stop");

startBtn.addEventListener("click", function(){
    t.start();
}, false);

stopBtn.addEventListener("click", function(){
    t.stop();
}, false);

这里有demo

答案 2 :(得分:0)

您可以使用java-script Closures进行此操作,将代码更改为:

function counter (action, tId) {
   var timer =setInterval(function() {  
    console.log(new Date());
 }, 1000);
 if(typeof tId!="undefined")
    window.clearInterval(tId);
   return function () {
    if(action=='stop'){
    counter('stop', timer)
   }
  }
 }

 $('#start').click(function() {
  counter('start');
 });
 $('#stop').click(function() {
   counter('stop'); 
 });

实际上我们所做的是如果动作停止,则使用interval-id重新调用该函数。

相关问题