JavaScript Local Storage Second Counter - javascript

my question is the following: Is it possible to create a second counter using local storage? I mean you load the page, the counter starts counting from 1 one by one. You reload the page at 5seconds, and the counter won't resets but continues the counting from 5. Is it possible?
I have a code with a simple sec counter, but I don't know how to make it workable with Local Storage
var seconds = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
seconds += 1;
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>

this way ?
<div id="seconds-counter">_</div>
<!-- button id="bt-stop-counter"> stop counter </button -->
const
counterLimit = 5 // <-- your counter limit value....
, div_s_counter = document.querySelector('#seconds-counter')
, btStopCounter = document.querySelector('#bt-stop-counter')
, timeRef_ls = localStorage.getItem('counterVal') || 0
, timeRef = (new Date()) - (timeRef_ls * 1000)
, CounterIntv = setInterval(() =>
{
let seconds = Math.floor(((new Date()) - timeRef) / 1000)
if (seconds >= counterLimit ) // stopCounter()
{
div_s_counter.textContent = seconds = counterLimit
clearInterval( CounterIntv )
}
div_s_counter.textContent = seconds
localStorage.setItem('counterVal', seconds.toString(10))
}
, 500)
;
div_s_counter.textContent = timeRef_ls
/* disable counter reset ------------------------------------
{
clearInterval( CounterIntv ) // to stop the counter
localStorage.removeItem('counterVal') // remove the counter
}
btStopCounter.onclick = stopCounter
------------------------------------------------------------*/

var el = document.getElementById('seconds-counter');
function incrementSeconds() {
var counter = window.localStorage.getItem("counter") ?? 0;
window.localStorage.setItem("counter", ++counter);
el.innerText = counter;
}
var cancel = setInterval(incrementSeconds, 1000);

Related

How to pause running countdown with button to redirect page?

Already i got this code in 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>
I would like to place button with pause in my html site - it will works like 'if i press the button while countdown is running it will be stopped, but if i click again it will resume'. I've tried to put clearInterval in code but it didn't work. I'm really an amateur when it comes to javascript.
Nothing special
(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>

Restart Timer Using Javascript

I try to use JavaScript to set timer for my quiz.(setInterval) but if I finish the quiz earlier and click on start button gain, the time will start counting at the time I stop the quiz. How can I restart the time after I click on the start button again? .
<script>
var seconds = 40;
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") <= 0) {
var value = seconds;
alert(value);
} else {
var value = localStorage.getItem("counter");
}
} else {
var value = seconds;
}
document.getElementById("divCounter").innerHTML = value;
var counter = function() {
if (value <= 0) {
localStorage.setItem("counter", seconds);
value = seconds;
} else {
value = parseInt(value) - 1;
localStorage.setItem("counter", value);
}
document.getElementById("divCounter").innerHTML = value;
};
var interval = setInterval(function() { counter(); }, 1000);
</script>
Based on your current code what you need to do to reset the counter is set value=seconds and removing the current value in localStorage.
So assuming you have a button like this in your HTML:
<button type"button" onclick="resetCounter()">Reset</button>
you can add a resetCounter() function in your code:
var resetCounter = () => {
value = seconds;
localStorage.removeItem("counter");
};

Increment issues

I have a timer going that adds 1 every second to the variable MenuTimer.
What I want is when the next button is pressed TillOpen The MenuTimer will stop having 1 added to it after that and a new variable to have 1 added instead PackTime
window.onload = function () {
var StopwatchSeconds= 00;
var StopwatchMinutes = 00;
var ShowSeconds = document.getElementById("seconds");
var ShowMinutes = document.getElementById("minutes");
var StartButton = document.getElementById("ButtonStart");
var Interval;
var menuTime;
var serviceTime;
var orders;
var menuAvg;
var serviceAvg;
StartButton.onclick= function(){
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
}
function startTimer () {
StopwatchSeconds++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
ShowMinutes.innerHTML = StopwatchMinutes;
StopwatchMinutes++;
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
}
}
Here's all of it. It half works but hopefully you get a better Idea of what i'm trying to go for.
var Interval;
var PackInterval;
var StopwatchSeconds= 00;
var StopwatchMinutes = 00;
var ShowSeconds = document.getElementById("seconds");
var ShowMinutes = document.getElementById("minutes");
var StartButton = document.getElementById("ButtonStart");
var TillOpenButton = document.getElementById("TillOpen");
var FinishButton = document.getElementById("Finish");
var ShowMenuTime = document.getElementById("MenuTime");
var ShowPackTime = document.getElementById("PackTime");
var ShowPackAvgSeconds = document.getElementById("PackerSeconds");
var ShowPackAvgMinutes = document.getElementById("PackerMinutes");
var ShowMenuAvgSeconds = document.getElementById("MenuMinutes");
var ShowMenuAvgMinutes = document.getElementById("MenuSeconds");
var DivisionSeconds = 60;
var TotalTime = 0;
var MenuTime = 0;
var PackTime = 0;
var AllMenuTimes = 0;
var AllPackTimes = 0;
var TotalMenuOrders = 0;
var TotalPackOrders = 0;
var MenuOrdersTotalSeconds = 0;
var PackOrdersTotalSeconds = 0;
var MenuAvgMinutes = 0;
var MenuAvgSeconds = 0;
var PackAvgSeconds = 0;
var PackAvgMinutes = 0;
StartButton.onclick = function(){
TotalMenuOrders + 1;
MenuTime = 0;
ShowMenuTime.innerHTML = MenuTime;
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
window.alert ("I work");
}
//This starts the timer. Inverval is a variable that holds the timer number.
function startTimer () {
StopwatchSeconds++;
TotalTime++;
MenuTime++;
AllMenuTime++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
StopwatchMinutes++;
ShowMinutes.innerHTML = StopwatchMinutes; // Makes this a string in html
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
}
// When the start button is pressed this function starts. it adds 1 to
Stopwatch, total and Menu every 1000 increments that Interval hits.
// This also says if StopwatchSeconds goes above 59 itll reset to 0 and if
its below itll keep counting.
TillOpenButton.onclick = function () {
PackTime = 0;
ShowPackTime.innerHTML = PackTime;
ShowMenuTime.innerHTML = MenuTime;
PackInterval = setInterval(startPackerTimer, 1000);
Interval+PackInterval;
clearInterval(Interval);
/* if (TotalMenuOrders < 1) {
AllMenuTimes / TotalMenuOrders = MenuOrdersTotalSeconds;
MenuOrderTotalSeconds % 60 = MenuAvgSeconds;
MenuAvgMinutes = Math.floor(MenuOrderTotalSeconds/60);
ShowMenuAvgMinutes.innerHTML = MenuAvgMinutes;
ShowMenuAvgSeconds.innerHTML = MenuAvgSeconds;
}
*/
}
// When this button is pressed it stops the first timer and the menu timer.
It then starts a new timer and function which add to the variable that will
show the total time.
// It does clear the variable Interval though
FinishButton.onclick = function (){
clearInterval(Interval);
ShowPackTime.innerHTML = PackTime;
clearInterval(PackInterval);
StopwatchSeconds = 0;
StopwatchMinutes = 0;
ShowSeconds.innerHTMl = 0 + StopwatchSeconds;
ShowMinutes.innerHTML = 0 + StopwatchMinutes;
AllPackTimes += PackTime;
TotalPackOrders++;
/*AllPackTimes/TotalPackOrders = PackOrderTotalSeconds;
PackOrderTotalSeconds % DivisionSeconds = PackAvgSeconds;
PackAvgMinutes = Math.floor(PackOrderTotalSeconds/60);
ShowPackAvgMinutes.innerHTML = PackAvgMinutes;
ShowPackAvgSeconds.innerHTML = PackAvgSeconds;*/
}
// When the Finish Button is pressed it clears everything. Resets
everything. except Menu Time, Total Time and PackTime. I need 3 new
variables to hold these to get the average.
function startPackerTimer () {
StopwatchSeconds++;
TotalTime++;
PackTime++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
StopwatchMinutes++;
ShowMinutes.innerHTML = StopwatchMinutes;
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
// Same deal but with the Till open button. Still adds onto
STopwatchSeconds so the variable doesn't change.
}
New solution, wich allows to create different timers and keep track of them:
//a method to setup a new timer
function Timer(Name){
this.timeElement=document.createElement("div");
(this.stopButton=document.createElement("button")).innerHTML="STOP";
(this.startButton=document.createElement("button")).innerHTML="START";
(this.Name=document.createElement("h1")).innerHTML=Name;
[this.Name,this.timeElement,this.startButton,this.stopButton].forEach(el=>document.body.appendChild(el));
this.stopButton.addEventListener("click",this.stop.bind(this));
this.startButton.addEventListener("click",this.start.bind(this));
this.seconds=0;
this.minutes=0;
}
Timer.prototype={
update:function() {
this.seconds++;
if(this.seconds > 59) {
this.seconds=0;
this.minutes++;
}
var secTemp="00"+this.seconds, minTemp="00"+this.minutes;
this.timeElement.innerHTML=minTemp.slice(minTemp.length-2)+":"+secTemp.slice(secTemp.length-2);
},
stop:function(){
if(this.interval) clearInterval(this.interval);
this.running=false;
if(this.onstop) this.onstop(this);
}
start:function(){
if(this.interval) clearInterval(this.interval);
this.interval = setInterval(this.update.bind(this), 1000);
this.running=true;
if(this.onstart) this.onstart(this);
}
};
This implements a Timer with OOP. So you can create multiple timers, and they wont influence each other.
You can create a timer like this:
var timer= new Timer("The Name");
You can also change events, set/read the times and check if running:
timer.start();//start the timer ( can also be done with the ui button)
timer.stop();
timer.onstart=()=>alert("Started!");
timer.onstop=()=>alert("Stopped!");
console.log(timer.running,timer.minutes,timer.seconds);
If you want to wait for multiple timers and to calculate the average if all of them stopped:
var timers=["Timer 1", "Timer 2"].map(name=>new Timer(name));//create two timers and store in array
timers.forEach(function(timer){
timer.running=true;
timer.onstop=function(){
if(timers.some(t=>t.running)) return;//if theres a running timer dont procceed
var seconds=timers.reduce((seconds,timer)=>seconds+=(timer.seconds+timer.minutes*60),0);
var average=seconds/timers.length;
alert("Average: "+average+"s");
};
});
http://jsbin.com/coduvohewu/edit?output
The old solution, adding a timer if the new button is pressed, and stops the old one then:
So you want to stop the current timer, and create a new one below that? Maybe you could refactor the code a bit, doing sth like this:
window.onload = function () {
var seconds= 0,minutes = 0;
var times=[];
var Interval;
var timeElement;
//a method to setup a new timer
function createTimer(dontsave){
if(times.length>3) return alert(times.map(el=>el.join(":")).join());
timeElement=document.createElement("div");
document.body.appendChild(timeElement);
if(!dontsave) times.push([minutes,seconds]);
}
createTimer(true);
//a method to let the timer run
function startTimer () {
seconds++;
if(seconds > 59) {
seconds=0;
minutes++;
}
var secTemp="00"+seconds,minTemp="00"+minutes;
timeElement.innerHTML=minTemp.slice(minTemp.length-2)+":"+secTemp.slice(secTemp.length-2);
}
//assign to buttons:
document.getElementById("ButtonStart").onclick= function(){
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
}
document.getElementById("ButtonNew").onclick=createTimer;
};
http://jsbin.com/mujisaweyo/edit?output
This simply creates a new div in the DOM if you press a button with the id ButtonNew . So the current time stays as a text in the old Element, and it keeps counting in the new one. Ive also added a zero filling...

setInterval and clearInterval through button click events

Here is my code:
window.onload = runThis;
function runThis() {
const txtMin = document.getElementsByClassName("min");
const txtSec = document.getElementsByClassName("sec");
function go() {
setInterval(countDown, 1000);
}
function countDown() {
timeNow = timeNow - 1;
timeSec = timeNow % 60; //remainder as seconds
timeMin = Math.round((timeNow/60) - (timeSec/60)); //minutes
txtMin[0].innerText =
(timeMin > 0 ?
(timeMin >= 10 ? `${timeMin}:` : `0${timeMin}:`)
: "00:");
txtSec[0].innerText =
(timeSec > 0 ?
(timeSec >= 10 ? timeSec : `0${timeSec}`)
: "00");
}
function stopIt() {
let x = setInterval(countDown, 1000);
clearInterval(x);
}
const btnStart = document.getElementsByClassName("start");
btnStart[0].addEventListener("click", go);
const btnStop = document.getElementsByClassName("stop");
btnStop[0].addEventListener("click", stopIt);
}
I am having trouble trying to set up setInterval and clearInterval.
2 buttons: start and stop. I want the function go to run when I click start to start the timer. That is all good. My problem is trying to stop the timer.
If I put let x = setInterval(countDown, 1000); outside the stopIt() function, it will automatically start the timer on windows.onload regardless of whether or not I click the start button but, in doing so, I can stop the timer.
If I put let x = setInterval(countDown, 1000); inside the stopIt() function like what I have here, I can start the timer whenever I want by clicking the start button, but now I can't stop the timer using clearInterval().
Any help is greatly appreciated. Thanks in advance!
Try to set the ID of the interval in the "go" function in a variable outside to be canceled inside the "stopIt" function, like this:
window.onload = runThis;
function runThis() {
var intervalID = null;
const txtMin = document.getElementsByClassName("min");
const txtSec = document.getElementsByClassName("sec");
function go() {
intervalID = setInterval(countDown, 1000);
}
function countDown() {
timeNow = timeNow - 1;
timeSec = timeNow % 60; //remainder as seconds
timeMin = Math.round((timeNow/60) - (timeSec/60)); //minutes
txtMin[0].innerText =
(timeMin > 0 ?
(timeMin >= 10 ? `${timeMin}:` : `0${timeMin}:`)
: "00:");
txtSec[0].innerText =
(timeSec > 0 ?
(timeSec >= 10 ? timeSec : `0${timeSec}`)
: "00");
}
function stopIt() {
clearInterval(intervalID);
}
const btnStart = document.getElementsByClassName("start");
btnStart[0].addEventListener("click", go);
const btnStop = document.getElementsByClassName("stop");
btnStop[0].addEventListener("click", stopIt);
}

Javascript Countdown Timer Repeat and Count total that repeat

I have javascript countdown timer from 25 -> 0.
var count=25;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count; // watch for spelling
}
div HTML
<span id="timer">25</span>
Now I want the countdown is repeat automatically after wait 5 seconds then it start again from 25 -> 0. And I want to count how many times that countdown repeat. Is it possible for that?
Please help.
You can try wrapping the entire code into a function (countTimers() in the example below) that runs every 30 seconds (5 seconds after each timer). Then, set a counter (timersCount in the example below) to count how many times that will run.
See the example below:
var timersCount = 0, stopped = false, count, counter; // make count, counter global variables so buttons can access them
var timerCounter = setInterval(countTimers, 30000);
countTimers(); // run countTimers once to start
function timer() {
count = count-1;
document.getElementById("timer").innerHTML=count;
if(count <= 0) {
clearInterval(counter);
return;
}
}
function countTimers() {
timersCount++;
// as per request in the comments, you can set a timer counter as well:
document.getElementById("totalcounter").innerHTML = timersCount;
count = 25;
counter = setInterval(timer, 1000);
}
// button code:
document.getElementById("reset").addEventListener("click", function() {
clearInterval(timerCounter);
clearInterval(counter);
count = 25;
document.getElementById("timer").innerHTML=count;
timersCount = 0;
document.getElementById("totalcounter").innerHTML = timersCount;
stopped = true;
});
document.getElementById("stop").addEventListener("click", function() {
if(stopped)
return;
clearInterval(counter);
stopped = true;
});
document.getElementById("start").addEventListener("click", function() {
if(!stopped)
return;
stopped = false;
counter = setInterval(timer, 1000);
setTimeout(function() {
clearInterval(counter);
timerCounter = setInterval(countTimers, 30000);
countTimers();
}, count*1000);
});
Timer: <span id="timer">25</span><br>
Number of times run: <span id="totalcounter">1</span>
<br><br>
<button id="reset">Reset</button>
<button id="stop">Stop</button>
<button id="start">Start (if stopped)</button>
var count=25;
var counter = null;
// reset count and timer
function reset_timer()
{
count = 25;
counter=setInterval(timer, 1000); //1000 will run it every 1 second
}
// init timer for first time
reset_timer();
function timer()
{
count--;
if (count <= 0)
{
clearInterval(counter);
setTimeout(reset_timer, 5000);
return;
}
document.getElementById("timer").innerHTML=count; // watch for spelling
}
setTimeout is a timer that runs one time and stop.
This approach uses Promises to the countdown work and generate an infinite loop,
if for some reason you need to stop/resume your counter you can reject the Promise chain and have a boolean to control the state:
let secondsCounter =
document.querySelector('#secondsCounter'),
totalCount =
document.querySelector('#totalCount'),
ttc = 1,
actualSecond = 25,
isPaused = false,
interval;
let countDown = time => new Promise( (rs, rj) => interval = setInterval( ()=>{
if (isPaused) {
return rj('Paused');
}
secondsCounter.textContent = --actualSecond;
if (actualSecond == 0){
actualSecond = time + 1;
clearInterval(interval);
rs();
}
}, 1000));
let loop = time => countDown(time).then( ()=>{
totalCount.textContent = ++ttc;
return Promise.resolve(null);
});
let infinite = () => loop(25)
.then(infinite)
.catch(console.log.bind(console));
let stop = () => {
clearInterval(interval);
isPaused = true;
}
let resume = () => {
console.log('Resumed');
isPaused = false;
loop(actualSecond).then(infinite);
}
let start_stop = () => isPaused ?
resume() : stop();
infinite();
Seconds : <div id="secondsCounter">25</div>
Times : <div id="totalCount">1</div>
<button onclick="start_stop()">Start/Stop</button>

Categories