简体   繁体   English

如何重新启动已设置间隔的倒数计时器? Javascript

[英]How to restart a countdown timer that has set interval? Javascript

http://jsfiddle.net/Xotic750/wwg8H/ http://jsfiddle.net/Xotic750/wwg8H/

function startTimer(m, s) {
    timer.textContent = m + ":" + s;
    if (s == 0) {
        if (m == 0) {
            return;
        } else if (m != 0) {
            m = m - 1;
            s = 60;
        }
    }
    
    s = s - 1;
    id = setTimeout(function () {
        startTimer(m, s)
    }, 1000);
}

Refer to the link above, when you click start for one time, it countdown from 5:00 in a normal way.参考上面的链接,当你点击一次开始时,它从5:00开始正常倒计时。 However, when you press the start button two times, the countdown is not normal?但是,按两次启动键,倒计时不正常? May i know how to tackle this problem?我可以知道如何解决这个问题吗? Thank you.谢谢你。 If possible, please provide a codepen demo.如果可能,请提供 codepen 演示。 Thank you谢谢

Clear previous timer when someone click on start button again.当有人再次单击开始按钮时清除上一个计时器。

start.addEventListener("click", function () {
   clearTimeout(id);
    startTimer(5, 0);
}, false);

Checkout updated fiddle: http://jsfiddle.net/Lthvxeda/1/结帐更新小提琴: http : //jsfiddle.net/Lthvxeda/1/

在设置新的setInterval之前,您需要清除之前的setInterval ,请使用clearInterval(id)

You should clear the timer on click before executing the timer.在执行计时器之前,您应该在单击时清除计时器。

Additional notes:补充说明:

I recommend using different conditions so it will be less nested and more readable.我建议使用不同的条件,这样嵌套更少,可读性更强。

Notice there is a bug in your program you should reset the seconds to 59, not 60 - because the second already has passed.请注意,您的程序中存在一个错误,您应该将秒数重置为 59,而不是 60 - 因为第二秒已经过去了。

This is a quick example :这是一个快速示例:

let timerId;

function renderCountDownTimer(minutes, seconds) {
  timer.textContent = minutes + ":" + seconds;
  if(seconds==0 && minutes==0) {
    return;
  }
  if(seconds == 0){
    minutes--;
    seconds = 59;
  } else {
    seconds--;
  }
  timerId = setTimeout(() => {
    renderCountDownTimer(minutes,seconds)
  },1000)
}

start.addEventListener("click", function () {
    clearTimeout(timerId)
    renderCountDownTimer(5, 0);
}, false);

Added the fiddle : https://jsfiddle.net/fqdhaxz7/1/添加小提琴: https : //jsfiddle.net/fqdhaxz7/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM