Resetting a Timer Back to 0 from Counter? - javascript

I have been googling for a solution for this problem, but many suggestions that I have found either freezes the counter or does nothing. counter.innerHTML = 0 just resumes where it left off after a second.
Here is my code:
let reset = document.getElementById('reset')
let counter = document.getElementById('counter')
let num = 0;
let timer = setInterval(countUp, 1000);
function countUp() {
counter.innerHTML = num++
}
//Reset timer
reset.addEventListener('click', stuff)
function stuff() {
clearInterval(timer)
}

What you have is mostly working, you just need to
clear the internal
reset the innerHtml to 0
let reset = document.getElementById('reset')
let counter = document.getElementById('counter')
let num = 0;
let timer = setInterval(countUp, 1000);
function countUp() {
counter.innerHTML = num++
}
//Reset timer
reset.addEventListener('click', stuff)
function stuff() {
counter.innerHTML = 0;
clearInterval(timer)
}
<button id="reset">reset</button>
<div id="counter" />

It's probably useful to put the logic that changes what you see in the page content in its own function: this will help you think about each part of the problem independently:
let resetBtn = document.getElementById('reset');
let counter = document.getElementById('counter');
let num = 0;
// Start the timer
let timer = setInterval(countUp, 1000);
// Use this to update the DOM (page content)
function updateUI () {
counter.textContent = num;
}
function countUp () {
// Increment the number
num += 1;
// Update the DOM
updateUI();
}
function reset () {
// Stops the interval
clearInterval(timer);
// Reset the number
num = 0;
// Update the DOM
updateUI();
}
// Update the UI the first time (before the counter reaches 1)
updateUI();
// Add the reset functionality to the button
resetBtn.addEventListener('click', reset);
<div id="counter"></div>
<button id="reset">Reset</button>

Related

setInterval's interval always changes to 1 second (1000ms) after a few iterations

I am just trying to create a simple counter using setInterval. However, after 5 seconds, the interval slows down to about 1000ms. I'm sure I am just overlooking something silly, but for the life of me I cant see it.
var btn = document.getElementById("btn");
var num = document.getElementById('num');
btn.addEventListener("click", startCounter);
var interval;
function startCounter(){
interval = setInterval(count, 100);
}
var idx = 0;
function count(){
idx++;
console.log(idx);
num.textContent = idx;
if(idx > 100) {
clearInterval(interval);
idx = 0;
}
}
<button id="btn">Click</button>
<div id="num" style="">0</div>

What's the best was to addEventListener onclick to the timer that I already have in place?

Apologies for the beginner question, I'm brushing up on my JS and this is my first post on here. I'm trying to add an event listener to this JS timer that's connected to my button .start-timer. What's the best way to go about it? Any help is appreciated, thanks!
const timeH = document.querySelector('h2');
let timeSecond = 30;
timeH.innerHTML = `${timeSecond}`;
const countdown = setInterval (()=>{
timeSecond --;
timeH.innerHTML = `${timeSecond}`;
if(timeSecond <= 0 || timeSecond < 1){
clearInterval(countdown);
}
},1000)
Make 2 functions to start and stop which only setInterval or clearInterval nothing special.
const timeH = document.querySelector('h2');
let timeSecond = 30;
timeH.innerHTML = `${timeSecond}`;
var countdown;
function start() {
clearInterval(countdown);
countdown = setInterval(() => {
timeSecond -= 0.1;
timeH.innerHTML = `${timeSecond.toFixed(1)}`;
if (timeSecond <= 0 || timeSecond < 1) {
clearInterval(countdown);
}
}, 100)
}
function stop() {
clearInterval(countdown);
}
document.querySelector(".start-timer").addEventListener('click', start);
document.querySelector(".stop-timer").addEventListener('click', stop);
<h2>hello</h2>
<button class="start-timer">start-timer</button>
<button class="stop-timer">stop-timer</button>

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

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);
}
}

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