【问题标题】:How to pause running countdown with button to redirect page?如何使用按钮暂停运行倒计时以重定向页面?
【发布时间】:2021-09-20 21:51:21
【问题描述】:

我已经在 javascript 中得到了这段代码

    <script type="text/javascript">
  var count = 20; // Timer
  var redirect = "https://www.instagram.com/"; // Target URL

  function countDown() {
    var timer = document.getElementById("timer"); // Timer ID
    if (count > 0) {
      count--;
      timer.innerHTML = "przekieruje cię za " + count + " sekund."; // Timer Message
      setTimeout("countDown()", 1000);
    } else {
      window.location.href = redirect;
    }
  }
</script>

我想在我的 html 站点中放置带有暂停的按钮 - 它的工作方式类似于“如果我在倒计时运行时按下按钮,它将停止,但如果我再次单击它将恢复”。我试图将 clearInterval 放入代码中,但没有奏效。说到javascript,我真的是个业余爱好者。

【问题讨论】:

  • 既然你使用的是timeout,那么你必须使用clearTimeout而不是clearInterval

标签: javascript html countdown


【解决方案1】:

没什么特别的

(async()=>{
    const timer = document.getElementById('timer');

    let timerId;
    let tf = false;
    let k = 7;

    const plusplus = async()=>{
        timer.innerHTML = k + ' dancing cows left';
        if(k < 1)clearInterval(timerId);
        else k--;
    };

    plusplus();
    timerId = setInterval(plusplus, 1000);
    document.getElementById('button').addEventListener('click', ()=>{
        if(!tf)clearInterval(timerId);
        else timerId = setInterval(plusplus, 1000);
        tf = !tf;
    });
})();
<button id="button">stop / resume</button>
<div id="timer"></div>

【讨论】:

  • 我的朋友,在倒计时到 0 后,我无法在此脚本中看到重定向,但感谢您的回复!
  • @Zimnyjestem if(k &lt; 1)clearInterval(timerId); 这一行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 2023-03-27
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多