Search code examples
javascripthtmltimer

How to start a countdown onclick with JS?


First, thank you for reading me. I am currently learning javascript, so... sorry for my code (and my bad english). Do not hesitate to make suggestion.

I am creating a (fake) website to book bikes in Toulouse (France). After users click on the #canvasbtn , i want to start a 20mn countdown / timer. At the end of the countdown, i would like to clear the sessionstorage & localstorage.

Problem : the timer is starting when the page load (not when you click on #canvasbtn). And I can't find how to clear the localstorage when the countdown hit 0.

https://github.com/ldoba/project-03

thank you for your help

const startingMinutes = 20;
let time = startingMinutes * 60;
const canvasbtn = document.querySelector('#canvasbtn');
const countdown = document.getElementById('timer');


//fonction minuteur 
function updateCountdown (){
    const minutes = Math.floor(time / 60);
    let seconds = time % 60;
    let timerStatus = true;
    seconds= seconds < 10 ? '0' + seconds : seconds;

    countdown.innerHTML = minutes + ' : ' + seconds;
    time--;

    if ((minutes + seconds) <= 0){
        clearInterval(interval);
        timerStatus = false;
    } else{
    }
}
//Interval pour rafraichissement chaque seconde
var interval = setInterval(updateCountdown, 1000);

//le timer est activé après avoir appuyer sur le bouton du canvas
canvasbtn.onclick = updateCountdown();


Solution

  • As I stated in the comments canvasbtn.onclick = updateCountdown(); is wrong because you are executing the function and assigning it to the click.

    Also setInterval is not accurate. And your countdown will not expire after 20 minutes after clicking the button. They would need to be sitting on the page for 20 minutes total (maybe you want that). You should be using date() to handle the diff in time.

    Below I used Date() for the difference and store the values in localstorage. I only start the timer if the value is in storage or if the button is clicked.

    const maxTime = 20 * 1000 * 60 * 60;
    
    const out = document.querySelector("#out");
    function msToTime(duration) {
      let milliseconds = parseInt((duration % 1000));
      let seconds = Math.floor((duration / 1000) % 60);
      let minutes = Math.floor((duration / (1000 * 60)) % 60);
      // let hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
    
      // hours = hours.toString().padStart(2, '0');
      minutes = minutes.toString().padStart(2, '0');
      seconds = seconds.toString().padStart(2, '0');
      milliseconds = milliseconds.toString().padStart(3, '0');
    
      //return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
      return minutes + ":" + seconds + "." + milliseconds;
    }
    
    let timer;
    function countDown() {
      const diff = Date.now() - startTime;
      const remaining = Math.max(maxTime - diff, 0);
      if (remaining > 0) {
        out.textContent = msToTime(remaining);
        timer = window.setTimeout(countDown, 20);
      } else {
         out.textContent = 'complete';
         window.localStorage.removeItem('timer')
      }
    }
    
    const storageTime = window.localStorage.getItem('timer');
    let startTime = storageTime ? +storageTime : null;
    
    if (startTime) countDown();
    
    document.querySelector("button").addEventListener("click", function (evt) {
      evt.preventDefault();
      if (timer) window.clearTimeout(timer);
      startTime = Date.now();
      countDown();
      window.localStorage.setItem('timer', startTime);
    });
    
    <div id="out"></div>
    
    <button>start</button>