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

How to stop a running countdown timer?

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

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

运行 计时器第一次运行时效果很好,但我需要它重新设置并从按下第二个按钮开始重新计算时间 - 但它运行不佳。我怎样才能停止计时器并再次 运行 它以获得新的输入值? 代码基于w3schhol example和另一个web example(你可以测试它):

 // 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(return 来自

var x = setInterval(function() 

) 但是没用...

这是一个例子:

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>

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

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);