Restart Timer Using Javascript - 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");
};

Related

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

Enable button when counter reaches zero

I have a button its disabled and i want to put a counter inside it, what i want to do is when the counter reaches zero it get enabled, how can i do that? in the code below the counter doesn't appear inside the button and i don't want the reset button i just want the button to be enabled when it reaches zero, here is what i have tried so far:
function Countdown()
{
this.start_time = "00:30";
this.target_id = "#timer";
this.name = "timer";
this.reset_btn = "#reset";
}
Countdown.prototype.init = function()
{
this.reset();
setInterval(this.name + '.tick()',1000)
}
Countdown.prototype.reset = function()
{
$(this.reset_btn).hide();
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
}
Countdown.prototype.tick = function()
{
if(this.seconds > 0) //|| this.minutes > 0)
{
if(this.seconds == 0)
{
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
}
this.update_target()
}
Countdown.prototype.update_target = function()
{
seconds = this.seconds;
if (seconds == 0) $(this.reset_btn).show();
else if(seconds < 10) seconds = "0" + seconds;
$(this.target_id).val(this.seconds)
}
timer = new Countdown();
timer.init();
$(document).ready(function(){
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="text" id="timer" disabled>Counter should be inside me, and enable me when it reaches 0</button>
<button id="reset">Reset</button>
This is much simpler than what you've got. Just use window.setTimeout().
Keep in mind that tracking time to a high precision is not super reliable in a browser. You may want to look at moment.js or use performance.now() for an easier API to handle that.
// Get refreence to span and button
var spn = document.getElementById("count");
var btn = document.getElementById("btnCounter");
var count = 5; // Set count
var timer = null; // For referencing the timer
(function countDown(){
// Display counter and start counting down
spn.textContent = count;
// Run the function again every second if the count is not zero
if(count !== 0){
timer = setTimeout(countDown, 1000);
count--; // decrease the timer
} else {
// Enable the button
btn.removeAttribute("disabled");
}
}());
<button id="btnCounter" disabled>Time left: <span id="count"></span></button>

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...

jQuery continues even if user has left the page

I want to make a page that runs a jQuery script when user gets in the page and the query runs even if user leaves the page or closes the browser. Is this possible?
if(localStorage.getItem("counter")){
if((localStorage.getItem("counter") >= 300) || (localStorage.getItem("counter") <= 0)){
var value = 300;
}else{
var value = localStorage.getItem("counter");
}
}else{
var value = 300;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function (){
if(value <= 0){
localStorage.setItem("counter", 0);
value = 0;
$( ".exit" ).trigger( "click" );
}else{
value = parseInt(value)-1;
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function (){counter();}, 1000);
This is my script. For more detail, this is a countdown from 300 that when user gets in the page it starts and I want to make it like it runs even if user has left the page till it gets 0.
I dare to answer your question and nevertheless hope this will help you. There is no chance to run this js-code after this tab has been closed but you can remember the time an user left your site by setting a time_leave that is set on each interval-round and when an user leaves your site using onbeforeunload:
var value;
if (localStorage.getItem('counter')) {
if ((localStorage.getItem('counter') >= 300) || (localStorage.getItem('counter') <= 0)) {
value = 300;
} else {
value = getElaspedTime();
}
} else {
value = 300;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function () {
if (value <= 0) {
localStorage.setItem('counter', 0);
value = 0;
//$('.exit').trigger('click');
} else {
value = parseInt(value) - 1;
localStorage.setItem('counter', value);
}
document.getElementById('divCounter').innerHTML = value;
// set "departure"-time
localStorage.setItem('time_leave', (new Date()).getTime());
};
function getElaspedTime() {
var now = new Date();
var timeLeft = + localStorage.getItem('time_leave');
timeLeft = new Date(timeLeft);
var passedSecs = (now.getTime() - timeLeft.getTime()) / 1000;
return parseInt(localStorage.getItem('counter')) - parseInt(passedSecs);
}
window.onbeforeunload = function(){
// set "departure"-time when user closes the tap
localStorage.setItem('time_leave', (new Date()).getTime());
};
var interval = setInterval(function () {
counter();
}, 1000);

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