在 Javascript 中,我如何使用 setInterval 和 clearInterval 来防止在设置新时间时使用多个计时器

In Javascript how do I use setInterval and clearInterval to prevent multiple timers when a new time is set

我有一个倒计时器,用户可以使用它来启动 YouTube 视频。当计时器达到“0”时,clearInterval() 停止倒计时并启动 YouTube 视频。但是,如果用户决定更改时间,无论我做什么,都会创建多个计时器。

如何在创建新计时器时删除旧计时器?

此处示例:http://js.do/code/130794

(设置一个定时器然后设置一个新的定时器,定时器建立而不是替换原来的定时器)

我在这个问题上花了几天时间,任何想法都将不胜感激

function countdown(){

 var today = new Date();

 // Goes and gets the alarm times from selection boxes
 var slhrss = document.getElementById('selectyhrs');
 var slhrs = slhrss.options[slhrss.selectedIndex].value;
 var slminss = document.getElementById('selectymins');
 var slmins = slminss.options[slminss.selectedIndex].value;
 var slsecss = document.getElementById('selectysecs');
 var slsecs = slsecss.options[slsecss.selectedIndex].value;

 // Assumes if the user selects before the actual time they want the alarm for tomorrow
 if (today.getHours() > slhrs){
     var target_date = new Date(today.setDate(today.getDate()+1));
     target_date.setHours( slhrs,slmins,slsecs,0 );
 }

 //Assumes if the user selects after the actual time they wan the alarm for today
 else{
     var target_date = new Date();
     target_date.setHours( slhrs,slmins,slsecs,0 );
 }

 // variables for time units
 var hours, minutes, seconds;

 // get tag element
 var countdown = document.getElementById('countdown');

 // update the tag with id "countdown" every 1 second
 var iv = setInterval(function () {

      // find the amount of "seconds" between now and target
      var current_date = new Date().getTime();
      var seconds_left = (target_date - current_date) / 1000;

      if (seconds_left < 0){
          clearInterval(iv);
          return;
      }

      // do some time calculations
      hours = parseInt(seconds_left / 3600);
      seconds_left = seconds_left % 3600;
      minutes = parseInt(seconds_left / 60);
      seconds = parseInt(seconds_left % 60);

      // format countdown string + set tag value
      countdown.innerHTML = '<h2>Time remaining</h2>' + '<span class="hours">' + hours + ' <b>Hours</b></span> <span class="minutes">' + minutes + ' <b>Minutes</b></span> <span class="seconds">' + seconds + ' <b>Seconds</b></span>';  
      if(hours + minutes + seconds == 0){
          document.getElementById("video").innerHTML = '<iframe src="http://www.youtube.com/embed/QH2-TGUlwu4?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>'
      }
 }, 1000);
}
function settimer(a,b,c){
  try{
    clearInterval(window[a]);
  }catch(e){};
   window[a]=setInterval(b,c);
  }

这样使用:

var timer1;
settimer("timer1",function(){},1000);
//you can still do:
clearInterval(timer1);

问题是您只在计时器用完时清除间隔,而不是在创建新计时器时。

如果您将 iv 设为全局范围的变量并在创建新计时器之前在倒计时中对其调用 clearInterval,它应该适合您。

我想这里已经解决了:http://js.do/benkelaar/clearinterval-and-setinterval-fixed