如何停止正在运行的倒数计时器?

时间:2019-12-19 10:53:33

标签: javascript html setinterval

我有一个文本框和一个按钮。按下该按钮将根据文本框值计算剩余时间。

例如,对于3600(=秒)的值,它将计算剩余时间:0天,0小时,59分钟59秒。

第一次运行计时器效果很好,但是我需要它重新设置并从第二次按下按钮开始计算时间-效果不佳。如何停止计时器并为新的输入值再次运行它? 基于w3schhol示例和另一个Web示例(您可以对其进行测试)的代码:

 // Set the date we're counting down to

    function setTimer()
    {

    var timeSpan = convert();
    //var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
    var countDownDate = new Date(timeSpan).getTime();

    // Update the count down every 1 second
    var x = setInterval(function() 
    {
 
  
      // Get today's date and time
      var now = new Date().getTime();
    
      // Find the distance between now and the count down date
      var distance = countDownDate - now;
    
      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
      // Output the result in an element with id="demo"
      document.getElementById("demo").innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";
    
      // If the count down is over, write some text 
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
          }
        }, 1000);


    }

    function convert()
    {
    var now = new Date()  
    var secondsSinceEpoch = Math.round(now.getTime() / 1000)  

     // Unixtimestamp
     var unixtimestamp = document.getElementById('timestamp').value;
     unixtimestamp = parseInt(unixtimestamp);
     secondsSinceEpoch = parseInt(secondsSinceEpoch);
     unixtimestamp = unixtimestamp +  secondsSinceEpoch;
     // Months array
     var months_arr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

     // Convert timestamp to milliseconds
     var date = new Date(unixtimestamp*1000);

     // Year
     var year = date.getFullYear();

     // Month
     var month = months_arr[date.getMonth()];

     // Day
     var day = date.getDate();

     // Hours
     var hours = date.getHours();

     // Minutes
     var minutes = "0" + date.getMinutes();

    // Seconds
     var seconds = "0" + date.getSeconds();

     // Display date time in MM-dd-yyyy h:m:s format
     var convdataTime = month+' '+day+', '+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
     //"Jan 5, 2021 15:37:25"
     document.getElementById('datetime').innerHTML = convdataTime;
     return convdataTime;
    }
 <!DOCTYPE HTML>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    p {
      text-align: center;
      font-size: 60px;
      margin-top: 0px;
    }
    </style>
    </head>
    <body>
    <input type='text' value='1490028077' id='timestamp'>&nbsp;
    <input type='button' id='convert' value='Convert' onclick='setTimer()'>

    <br><br>
    <span id='datetime'></span>
    <p id="demo"></p>

    </body>
    </html>

我试图放置一个计数器变量,并且一旦变量== 2(从

返回),就调用return
var x = setInterval(function() 

) 但这没用...

这里是一个示例:

The timer freaks out from the second button press

2 个答案:

答案 0 :(得分:1)

var interval;
function setTimer()
    {

clearInterval(interval)

    var timeSpan = convert();
    //var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
    var countDownDate = new Date(timeSpan).getTime();

    // Update the count down every 1 second
    interval = setInterval(function() 
    {
 
  
      // Get today's date and time
      var now = new Date().getTime();
    
      // Find the distance between now and the count down date
      var distance = countDownDate - now;
    
      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
      // Output the result in an element with id="demo"
      document.getElementById("demo").innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";
    
      // If the count down is over, write some text 
      if (distance < 0) {
        clearInterval(interval);
        document.getElementById("demo").innerHTML = "EXPIRED";
          }
        }, 1000);


    }

    function convert()
    {
    var now = new Date()  
    var secondsSinceEpoch = Math.round(now.getTime() / 1000)  

     // Unixtimestamp
     var unixtimestamp = document.getElementById('timestamp').value;
     unixtimestamp = parseInt(unixtimestamp);
     secondsSinceEpoch = parseInt(secondsSinceEpoch);
     unixtimestamp = unixtimestamp +  secondsSinceEpoch;
     // Months array
     var months_arr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

     // Convert timestamp to milliseconds
     var date = new Date(unixtimestamp*1000);

     // Year
     var year = date.getFullYear();

     // Month
     var month = months_arr[date.getMonth()];

     // Day
     var day = date.getDate();

     // Hours
     var hours = date.getHours();

     // Minutes
     var minutes = "0" + date.getMinutes();

    // Seconds
     var seconds = "0" + date.getSeconds();

     // Display date time in MM-dd-yyyy h:m:s format
     var convdataTime = month+' '+day+', '+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
     //"Jan 5, 2021 15:37:25"
     document.getElementById('datetime').innerHTML = convdataTime;
     return convdataTime;
    }
<!DOCTYPE HTML>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    p {
      text-align: center;
      font-size: 60px;
      margin-top: 0px;
    }
    </style>
    </head>
    <body>
    <input type='text' value='1490028077' id='timestamp'>&nbsp;
    <input type='button' id='convert' value='Convert' onclick='setTimer()'>

    <br><br>
    <span id='datetime'></span>
    <p id="demo"></p>

    </body>
    </html>

答案 1 :(得分:0)

这是基于类的方法的一个示例(因此您不需要全局变量);

class Timer {
  constructor(logTicks = false) {
    this.interval = null;
    this.logTicks = logTicks;
  }
  start() {
    this.interval = setInterval( () => {
      if (this.logTicks) { console.log('Tick'); }
    }, 1000);
  }
  stop() {
    if (this.interval) { clearInterval(this.interval); }
  }
}


// Usage
const timer = new Timer(true);
timer.start();

setTimeout( () => { timer.stop(); }, 10000);