Home > Net >  javascript countdown timer
javascript countdown timer

Time:12-30

I want to create a countdown timer with javascript that will count down every six minutes. When it gets to 00 I will start from 6 minutes. It will continue like this forever. If the browser is refreshed, this countdown will continue. Even if the browser is refreshed, the countdown will not start again from 6 minutes until 00. How can I do this? Someone help with the code.

CodePudding user response:

Welwome to SO. Please, before asking for help try to provide some code before.

For this time, we will help.

let countdown = 6 * 60;

setInterval(function() {
  countdown--;

  if (countdown === 0) {
    countdown = 6 * 60;
  }

  document.getElementById("countdown").innerHTML = countdown;
}, 1000);

Note that if the browser is refreshed, everything will reinitialize. To keep track, you'll need a database or store in client browser.

CodePudding user response:

Make a button with the onclick function starting the timer using the setInterval function that has a callback that decreases a second each second from the 6 minutes.In the callback, store the time into localstorage, and make the startingTime value restore from the localstorage time value if the localstorage time value is not 0.

const start = document.querySelector("#start")
const timeP = document.querySelector("#time")

let interval;

const startingTime = 360

let time = startingTime || window.localStorage['time']

console.log(window.localStorage['time'])

const setLocalStorage = () => {
  console.log(time);
  window.localStorage['time'] = time}


if (time <= 0) {
  time = startingTime
  setLocalStorage()
}

function calc(s) {
minutes = (s - s % 60) / 60;
seconds = s % 60;
  return minutes   ":"   seconds
}

function callback() {
  
  console.log(time);
  time--;
  
  timeP.innerHTML = calc(time);
   
  if (time <= 0) {
  time = startingTime;
  clearInterval(interval);
  start.classList.remove("invis")
  timeP.classList.add("invis")
  }
  
  setLocalStorage();
  
}


function startTimer() {
    interval = setInterval(callback, 1000);
    start.classList.toggle("invis");
    timeP.classList.remove("invis")
}

start.onclick = startTimer
.invis {
display: none
}

#start {
  color: black;
  background-color: red;
}

#time {
  color: black;
  
}
<button id="start">START</button>
<p1 id="time" ></p1>

CodePudding user response:

If you want the timer "not to pause" to run even after you exit the browser then:

you could store the value of Date.now() in localstorage or wherever you want and get the value on load and subtract that value from the current Date.now() and you have the difference between the times now you can use that difference to do what you want.

  • Related