javascript countdown timer - javascript

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.

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.

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" class="invis"></p1>

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

How to synchronise a timer for everyone client

I have a working timer, but it runs from 25 seg every time who the website is visited by a client, I want to synchronise it. F.E. if i visit my webpage in mY Pc, and when it show 15seg left, i visit it from other pc and i want it to show 15 left too.
function timerr(){
var initial = 25000;
var count = initial;
var counter;
var initialMillis;
function timer() {
if (count <= 0) {
clearInterval(counter);
return;
}
var current = Date.now();
count = count - (current - initialMillis);
initialMillis = current;
displayCount(count);
function displayCount(count) {
var res = count / 1000;
if (res<0.1){
document.getElementById("timer").innerHTML = "";
}
else{
tiempo = res.toPrecision(count.toString().length);
tiempo_corto = tiempo.slice(0,-1);
document.getElementById("timer").innerHTML = tiempo_corto;
}
}
clearInterval(counter);
initialMillis = Date.now();
counter = setInterval(timer, 10);
}
If you want everyone to have the same timer count down every 25 seconds and stop at the exact same time, then you can simply use timestamps to keep everything in sync. Here's an example countdown timer that'll restart every 6 seconds (from 5 to 0) and will hit zero at the exact same time for everyone (unless their computer clock is off).
const timerElement = document.getElementById('timer')
const TIMER_DURATION = 6
function step() {
const timestamp = Date.now() / 1000
const timeLeft = (TIMER_DURATION - 1) - Math.round(timestamp) % TIMER_DURATION
timerElement.innerText = timeLeft
const timeCorrection = Math.round(timestamp) - timestamp
setTimeout(step, timeCorrection*1000 + 1000)
}
step()
<p id="timer"></p> seconds
Try it - open this page up in two different tabs and run it. This is set up to automatically account for the fact that setTimeout doesn't always trigger at the delay you asked it to do so (it'll adjust the next setTimeout with a timeCorrection value to correct these issues).
The basic principle is that we're getting the current timestamp and modding it by the amount of time we want this timer to last (6 seconds in the above example). This value will always be the same for everyone, and will always be a number that ranges from 0 to 5. It will also be a number that counts up every second (which is why we then subtract (TIMER_DURATION - 1) from it, to cause the number to count down instead).

How can i get counter from setInterval?

I have interval that needs to do some http requests after one minute
setInterval(() => {
this.takeTableDataCallInterval();
}, 60000);
How can i get counter minus from my Interval Number ?
For example every one second i want to show something like
60 seconds Left until new call is maked
59 seconds Left until new call is maked
When it comes to 0 it should start over
Here is an example:
it works every one second in order to do the countdown but once it reach to the 60 it resets the countdown and does the request.
const timer = document.querySelector('#timer');
let counter = 60;
setInterval(() => {
if (counter === 0) {
//this.takeTableDataCallInterval();
counter = 60;
}
else {
timer.innerHTML = `${counter} seconds left`;
counter--;
}
}, 1000);
<p id="timer"></p>
Counting shorter setInterval periods is one way of doing this, although timings here are rarely accurate enough to decently measure the passage of time, and you'll see drift (i.e. 60 one second intervals won't sum to exactly 60s)
Instead, record a "due time" with a high accuracy using performance.now()
let dueTimeMs = performance.now() + 60000;
then set an interval with relatively short time
setInterval(() => {
const nowMs = performance.now();
const timeUntilDueMs = dueTimeMs - nowMs;
// report remaining time
if(timeUntilDueMs <= 0){
// do something
dueTimeMs += 60000;
}
},100);
Try this:
let timeout;
function resetTimeout(limit) {
timeout = limit;
}
function serviceCall() {
console.log('Service call made')
}
setInterval(() => {
if(timeout == 0 || timeout == null) {
(timeout == 0) ? serviceCall() : ''
resetTimeout(60);
}
console.log(`${timeout}s left until new call is made`)
timeout --;
}, 1000);

how to store timer in localstorage and resume on page reload

I have a timer on my page that starts counting from the moment the page is loaded, shows it in minutes and seconds. There is also a save button that saves this time, and when we reload the page, the timer should start counting from the time we saved. But on reboot it writes NAN: NAN. How can I save and resume timing correctly?
let timerInterval;
let timerStart;
let time = 0;
function updateTime() {
time++;
let mins = parseInt(time / 60);
let secs = time % 60;
if(mins < 10) {
mins = '0' + String(mins);
}
if(secs < 10) {
secs = '0' + String(secs);
}
document.querySelector('#timespan').innerHTML = `${mins}:${secs}`;
}
function startTimer() {
timerInterval = setInterval(updateTime, 1000);
time = 0;
timerStart = true;
};
function stopTimer() {
clearInterval(timerInterval);
time = 0;
timerStart = false;
}
document.querySelector('.save-btn').addEventListener('click', () => {
localStorage.setItem('currentTime', document.querySelector('#timespan').innerHTML);
}
window.addEventListener('load', () => {
document.querySelector('#timespan').innerHTML = localStorage.getItem('currentTime');
}, false );
You need to parse localStorage content to hydrate your global time variable before after you call startTimer (which is not shown in the code you posted).

Cant Make a function run again

I made a timer that will reach zero.
and when it reaches zero make the timer run again.
the timer goes back to the starting number but doesnt run again.
also when i call it again the numbers just start to jump.
the code:
var timerPlace = document.getElementById('timer');
var timerP = document.getElementById('timerHard');
var stopTimer;
var toStop;
function timeMed() {
console.log('im in!')
var counter = 0;
var timeLeft = 5;
timerPlace.innerHTML = '00:45';
function timeIt() {
console.log('here')
counter++
timerPlace.innerHTML = convertSeconds(timeLeft - counter);
if (timerPlace.innerHTML == '00:00') {
clearInterval(stopTimer);
resetExercise();
timeMed();
}
}
function convertSeconds(s) {
var sec = s % 60;
var min = Math.floor((s % 3600) / 60);
return ('0' + min).slice(-2) + ':' + ('0' + sec).slice(-2);
}
if (!stopTimer) {
stopTimer = setInterval(timeIt, 1000);
}
}
You only call setInterval() when stopTimer is not set. But after the countdown completes, stopTimer is still set to the ID of the old interval timer, so you don't restart it. You should clear the variable when you call clearInterval().
if (timerPlace.innerHTML == '00:00') {
clearInterval(stopTimer);
stopTimer = null;
resetExercise();
timeMed();
}
Modern ES6 Approach and best practices.
I've decided to take the chance and refactor your code a little with Javascripts best practices in mind.
I've added comments which explain the code, and the engineering considerations.
The baseline for the timer is taken from the excellent answer here: https://stackoverflow.com/a/20618517/1194694
// Using destructuring on the paramters, so that the keys of our configuration object,
// will be available as separate parameters (avoiding something like options.duraitons and so on.
function startTimer({duration, onUpdate , infinite}) {
let timer = duration, minutes, seconds;
let interval = setInterval(function () {
minutes = parseInt(timer / 60);
seconds = parseInt(timer % 60);
// you can also add hours, days, weeks ewtc with similar logic
seconds = seconds < 10 ? `0${seconds}` : seconds;
minutes = minutes < 10 ? `0${minutes}` : minutes;
// calling your onUpdate function, passed from configuraiton with out data
onUpdate({minutes, seconds});
if (--timer < 0) {
// if infinite is true - reset the timer
if(infinite) {
timer = duration;
} else {
// Clearing the interval + additonal logic if you want
// I would also advocate implementing an onEnd function,
// So that you'll be able to decide what to do from configuraiton.
clearInterval(interval);
}
}
}, 1000);
}
const duration = 5;
const displayElement = document.querySelector("#timer");
startTimer({
duration,
onUpdate: ({minutes, seconds}) => {
// now you're not constraint to rendering it in an element,
// but can also Pass on the data, to let's say your analytics platform, or whatnot
displayElement.textContent = `${minutes}:${seconds}`;
},
infinite: true
});
<div id="timer">
</div>

repeating timer functionality and logic

I'm creating pomodoro timer- interval should repeat with different duration after first one completes. simplified non working exampe:
var firstDuration=5;
var secondDuration=10;
var timer=setInterval(()=>{
firstDuration--
if (firstDuration<0){
clearInterval(timer) ..
//secondDuration-- dont know how to continue..
What is the best way to implement such functionality? Also i plan to use Date.now() rather than -- .
If i've understood the requirements correctly, this will do what you want. It will have a timer go off every second until 20 minutes have elapsed, then every second until 5 minutes have elapsed. At that point it starts over with the 20 minute countdown.
const workDurationSeconds = 20 * 60;
const breakDurationSeconds = 5 * 60;
function startCountdown(session) {
let duration;
if (session === 'work') {
duration = workDurationSeconds;
} else {
duration = breakDurationSeconds;
}
let id = setInterval(() => {
duration--;
if (duration <= 0) {
clearInterval(id);
startCountdown(session === 'work' ? 'break' : 'work');
}
}, 1000);
}

Categories