setInterval in a countdown timer gets executed multiple times after first round - javascript

Hope y'all staying safe
i'm trying to figure out a simple countdown timer with these codes below:
what happens is first time i click it it goes fine, counting down the number by seconds as how it should work. however from second time it becomes "faster", it goes 2 numbers per second. 3rd time it goes 3 numbers per second, or if i clicked it a few times at once it also goes "faster"
I assume its because the interval is adding up (somehow?) and execute the same code n* times per
second. but i don't know where /how i should clear the interval completely each time?
hope this make sense to you guys
and thanks in advance for help
function makeTimer(){
document.getElementById("button-1").innerHTML = "Stop Countdown";
timeLeft = document.getElementById("set-time").value;
// buttonChange()
document.getElementById("set-time").value = ""
setInterval(function(){
if(timeLeft <=0){
clearInterval(timeLeft = 0)
}
document.getElementById("timer-id").innerHTML = timeLeft+"s"
timeLeft = timeLeft - 1
},1000)
}
function toggleTimer(){
// clearInterval(timeLeft)
button = document.getElementById("button-1")
if(button.innerHTML ==='Click to countdown'){
makeTimer()
}else if(button.innerHTML=== "Stop Countdown"){
clearInterval(timeLeft = 0)
button.innerHTML = "Click to countdown"
}
}

You're using clearInterval incorrectly.
setInterval returns a reference to your timer, which you then have to pass to clearInterval to stop it.
Example:
var myTimer = setInterval(myFunction, 1000); //Starts the timer
clearInterval(myTimer); //Stops the timer

Related

Update Element at every 10th Second, i.e., like at 12:30:10, 12:31:10, etc

The question: How to update element at every 10th Second, i.e., like at 12:30:10, 12:31:10, etc
The following technically works and does as I need, but how am I supposed to do this in the right way? That is, optimally, in terms of code and execution time?
setInterval(function(){
var now = new Date();
if (now.getSeconds() == 10) {
$('#jama').load('jama.php');
}
},1000);
The Problem: I think what you're asking is: To check every for every tenth second, i.e., 12:30:10 is a tenth second, but check every ten seconds (12:30:13, 12:30:23, etc.) is not.
The Solution: In that case, use setTimeout(), running it every second, to find the tenth second, and when you find the tenth second, then just setInterval() as you're doing now.
The Advantage: What's the advantage? Once you find the tenth second, you can change setInterval()'s delay from 1000 to 60000, since we know the next tenth second will be 60 seconds away. This reduces how often the code needs to check, and it also removes the now() object and the unnecessary checking.
The Code: Working demo below.
var myinterval = false;
function findTenthSecond() {
if(!myinterval) {
findTenthSecond_async();
}
}
function findTenthSecond_async() {
setTimeout(function(){
var now = new Date();
console.log("Check second: " + now.getSeconds() + "|");
if (now.getSeconds() == 10) {
myinterval = true;
// your code is here
setInterval(function(){
console.log ("Load jama.php");
$('#jama').load('jama.php');
},60000); // updated the second count to 60 seconds
} else {
findTenthSecond();
}
}, 1000);
}
findTenthSecond();

Create a number sequence function that runs on a timer [duplicate]

This question already has answers here:
Javascript: Increment count by 5 for a variable inside a setInterval() function
(4 answers)
Closed 4 years ago.
I need to take a number (ex. 100), then in 10 seconds add 100 to it. In another 10 seconds, add 100 again to create a running total.
How would I create a function to keep a running total, and have it on a timer that fires every 10 seconds?
You can do it using setInterval
Here in eachInterval function it calls the function (given in setInterval ) and add the value to total and display in console. You can pass time in function as per you need
let total = 100;
let interval;
function eachInterval(time){
interval = setInterval(()=>{
total+=100;
console.log(total)
},time)
}
setTimeout(()=>{
clearInterval(interval)
},5000)
eachInterval(1000)
function createsequence(){
var number = 100;
console.log(number)
//setInterval run at gap of 10 secs use it instead of timer
var interval = setInterval(function(){
//increment number
number += 100;
console.log(number)
},10000);
//10000ms is 10 secs
}
createsequence()

Javascript Second Counter

On my website, I am trying to count (and display) how many seconds (not minutes or hours) the user has been on my site. So, if they have been on it for 5 minutes, it will display 300, Not 5 minutes.
I am Very Unexperienced with JavaScript, So please help.
You can use the setInterval function to run another function as often as you choose. For example:
var seconds = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
seconds += 1;
el.innerText = "You have been here for " + seconds + " seconds.";
}
var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>
If you run this snippet, you'll see the counter working.
The setInterval function takes two parameters:
the function you want to call
the number of milliseconds between calls
Since you want to call increment the counter every second, you want to use 1000 milliseconds (1 second).
For more details, see the MDN documentation for setInterval.
My answer is similar to the one above but I'll give it anyway. This will only work on a single page so hopefully your site already runs on AJAX.
window.setInterval((function(){
var start = Date.now();
var textNode = document.createTextNode('0');
document.getElementById('seconds').appendChild(textNode);
return function() {
textNode.data = Math.floor((Date.now()-start)/1000);
};
}()), 1000);
You've been on this page for <span id=seconds></span> seconds.

Simple javascript counter no frills, just count

I have the number 3,453,500 it needs to increase by +1 every 4 seconds.
Need to keep the formatting the same (commas in the right place)
(also is there a way that this can count continuously without the refreshing to the lowest number on page refresh?)
Should be pretty simple...
Retrieve the number from local storage and display it
var num = +localStorage.getItem('num') || 3453500;
document.getElementById('display').innerHTML = num.toLocaleString();
Setup an interval to update the number every 4 seconds, save it and display it
setInterval(function() {
num++;
document.getElementById('display').innerHTML = num.toLocaleString();
localStorage.setItem('num', num);
}, 4000);
JSFiddle

How to reset stop watch for multiple stop watch time?

I am trying to use multiple stop watch timer by using anchor tag.I have successfully done but I am not able to add a functionality like if I clicked first timer,It will start timer from zero,when I clicked second one,first timer's value will be zero and second one will start timer from zero.I am giving my working code below :
JS:
var digit=0;
var hrs = 0;
var min=0;
var time;
var timer_is_on=0;
var id;
function timer(id){
//[Old] - this should be placed after you increment digit
// document.getElementById("secs").innerHTML = digit
//alert("I am testing value"+id);
//[New]
// get the numerical value for seconds,minutes,hours
digit = parseInt(document.getElementById("secs"+id).innerHTML);
min = parseInt(document.getElementById("mins"+id).innerHTML);
hrs = parseInt(document.getElementById("hrs"+id).innerHTML);
// increment;
digit=digit+1;
if(digit>"59"){
min = parseInt(min)+1;
// why is this code here
var count = min.toString().length;
digit=0;
}
// [old] checking if second is greater than 59 and incrementing hours
// if(digit>"59"){
// [new] check if minute is greater than 59
if(min > "59"){
hrs=parseInt(hrs)+1;
digit=0;
min=0; // minute should be reset as well
}
// set the values after all processing is done
document.getElementById("secs"+id).innerHTML = format(digit);
document.getElementById("mins"+id).innerHTML= format(min);
document.getElementById("hrs"+id).innerHTML=format(hrs);
}
function activate(id){
if(!timer_is_on){
timer_is_on=1;
// time = setTimeout("timer()",1000) will only call it once , use setInterval instead
time=setInterval("timer("+id+")",1000);
}
else {
timer_is_on=0;
clearInterval(time); // clear the timer when the user presses the button again and reset timer_is_on
}
return id;
}
// left pad zero if it is less than 9
function format(time){
if(time > 9)
return time;
else return "0"+time;
}
And The HTML code I have used are :
Click here to start the timer
<span id="hrs1" >00</span>:<span id="mins1" >00</span>:<span id="secs1">00</span></strong>
<br/>
Click here to start the timer
<span id="hrs2" >00</span>:<span id="mins2" >00</span>:<span id="secs2">00</span>
Here is my working js fiddle demo : http://jsfiddle.net/EPtFW/1/
as you are using same method activate() to start second timer, it will make first timer as zero if timer already running.
Solution is "you have to maintain multiple unique timer ids for multiple timers"
For Example, let's say you have T1 and T2 timers to start time;
var timerMap={};
timerMap[createUniqueId for T1] = setInterval();
timerMap[createUniqueId for T2] = setInterval();
to clear timers
clearInterval(timerMap[createUniqueId for T1]);
clearInterval(timerMap[createUniqueId for T2]);
In your case, you have to have createUniqueId and adding to timerMap should be in activate() method. they will work independently.

Categories

Resources