简体   繁体   中英

How do I stop my countdown timer from executing after it has reached the deadline on refresh of my browser

This is how the JavaScript looks like. I tried searching for solutions but couldn't find. Please I need detailed solutions. Online I kept seeing cookies but I don't know how to use it in this case.

  function countDown() {
      var now = new Date();
      var eventDate = new Date(2020, 5, 22);

      var currentTime = now.getTime();
      var eventTime = eventDate.getTime();

      var remTime = eventTime - currentTime;

      var s = Math.floor(remTime / 1000);
      var m = Math.floor(s/60);
      var h = Math.floor(m/60);
      var d = Math.floor(h/24);

      h %= 24;
      m %= 60;
      s %= 60;

      h = (h < 10) ? "0" + h: h;
      m = (m < 10) ? "0" + m: m;
      s = (s < 10) ? "0" + s: s;

      document.getElementById("days").textContent = d;
      document.getElementById("days").innerText = d;

      document.getElementById("hours").textContent = h;
      document.getElementById("minutes").textContent = m;
      document.getElementById("seconds").textContent = s;

      var t = setTimeout(countDown, 1000);

      if (d == 0 && h == 0 && m == 0 && s == 0) {
        clearTimeout(t);
        document.getElementById("demo").innerHTML = "Happy Birthday!"
      }
  }
  countDown();
</script>

The trouble with your code is in the date checking logic.

Checking with == will only give you a truthy response if the datetime (or part thereof) is the same as the value you're checking it against.

However, you need to check whether the date is already past. To do this, you need to use a < or <= operator.

Here's an example of what I mean. The info is console.log ed instead, you can re-implement the DOM editing you have in your question.

 function countDown() { var now = new Date(); var eventDate = new Date(2020, 4, 22); // 22 May 2020 var currentTime = now.getTime(); var eventTime = eventDate.getTime(); var remTime = eventTime - currentTime; var s = Math.floor(remTime / 1000); var m = Math.floor(s/60); var h = Math.floor(m/60); var d = Math.floor(h/24); h %= 24; m %= 60; s %= 60; h = (h < 10)? "0" + h: h; m = (m < 10)? "0" + m: m; s = (s < 10)? "0" + s: s; var t = setTimeout(countDown, 1000); // This if statement only runs exactly on eventDate if (d == 0 && h == 0 && m == 0 && s == 0) { document.getElementById("demo").innerHTML = "Happy Birthday;" } // This if statement will run if we're past or exactly on eventDate if (remTime <= 0) { clearTimeout(t). } // This console.log shows that the numbers become negative after the date console,log(remTime, d,h,m;s); } countDown();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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