How to stop timer on loop with delay jQuery - javascript

I have made loop which has delay every 10 sec. I set a timer for 10 sec. But its not stopping after 3 loop.... any ideas ? What I do wrong ? After 2 loop I am checking if it 3d loop I am clearing interval but as you can see it cant clear ?
What I did so far: https://jsfiddle.net/56n720qm/2/
jQuery(document).ready(function() {
var i = 0;
var intervaltime;
var fiveMinutes = 10 * 1;
var display = document.querySelector('#timer');
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
intervaltime = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function stopINT(){
clearInterval(intervaltime);
}
function myLoop () {
if(i > 0){time = 10000;}else{time=0;} //every 10 s.
setTimeout(function () {
//postFB(i);
//alert(i);
i++;
if(i == 3){
stopINT();
}
if (i <= 2) {
startTimer(fiveMinutes, display);
myLoop();
}
}, time)
}
myLoop();
});

You're starting a new interval without clearing the first one, so at one point multiple intervals are running at the same time.
Add the line clearInterval(intervaltime); here to solve your problem.
if (i <= 2) {
clearInterval(intervaltime);
startTimer(fiveMinutes, display);
myLoop();
}
Check the fiddle out.
Also, you may want to consider changing the variable time from 10000 to 11000 to prevent the loop from finishing too soon.

Related

How do I stop 10 seconds timer in Javascript?

I can't seems to be able to stop the timer when it reaches zero. It will just repeat back to the original timing! See my codes below.
What I am trying to achieve is, once timer is 0, it will replace 00:00 with the text "Your time is up".
HTML:
<div class="quizTimer right">
<span>Timer:<br /><span id="qTimer"></span></span>
</div>
This is the Javascript which I did:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
console.log(display.textContent);
if (--timer < 0) {
timer = duration;
clearInterval(timer); // this piece of code didnt stop the timer
}
}, 1000);
}
window.onload = function () {
var oneMinute = 10 * 1,
display = document.querySelector('#qTimer');
startTimer(oneMinute, display);
};
clearInterval() expects a reference to the interval to be passed.
You're passing timer, which is not a reference to the interval - it's an integer from the passed-in function param.
Assign your interval to a variable and reference that when you want to clear it.
let foo = setInterval(() => {
/* code... */
clearInterval(foo);
}, 1000);
You just need to capture the interval id returned by setInterval() and use that:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var id = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
console.log(display.textContent);
if (--timer < 0) {
timer = duration;
clearInterval(id); // uses returned id
}
}, 1000);
}

timer pop up wont stop looping when time is up

trying to create a timer that starts when button is clicked and send a pop up when time is up on my game
I have tried breaking the loop but when this happens pop up no longer appears
document.getElementById('start').addEventListener('click', function (){
var oneMinute = 60,
display = document.querySelector('.timer');
startTimer(oneMinute, display);
render();
});
function startTimer(duration, display){
var timer = duration, minutes, seconds;
setInterval(function (){
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
document.querySelector('button').addEventListener('click', function(){
render();
})
if (--timer <= 0) {
timer = "0.00";
clearInterval(timer);
swal.fire(`YOU FAILED FINAL SCORE ${points}`)
}
}, 1000)
};
render();```
Your issue is here var timer = duration and here clearInterval(timer).
duration is a parameter and not an interval ID which clearInterval requires that's set by setInterval.
So really you want to reference the interval and clear by the same reference.
var interval = setInterval(function (){
...
}, 1000);
Replace your clearInterval(timer); with clearInterval(interval);

How to stop javascript timer from resetting when it completes

I am building a form that a I need a simple 10 minute javascript countdown timer to display in. I have found and am using the code at the top of the page here: The simplest possible JavaScript countdown timer? .. It does exactly what I need it to, but I need the timer not to reset when it reaches 00:00. I am a novice when it comes to Javascript, so any help would be appreciated.
I looked through the posting on The simplest possible JavaScript countdown timer? .. but was unable to see anyone that specifically talked about stopping the timer from resetting when it ended.
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 10,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
The timer works as I need it to, but it resets every time it reaches 0. I just need it to start on page load and stop at 10 minutes. I am just reminding my form users to save their draft every 10 minutes.
Try this:
var myInterval = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myInterval);
}
}, 1000);
Thanks for all the help. I found another piece of code that did the job for me. I'll share below for anyone else to use.
//Countdown Timer
var startTime = 10; //set countdown in Minutes
var doneClass = "done";
var blinkerClass = "blink";
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var intervalLoop = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
for(var i=0;i<display.length;i++){
display[i].textContent = minutes + ":" + seconds;
}
if (--timer < 0) {
for(var i=0;i<display.length;i++){
display[i].classList.add(doneClass);
display[i].classList.add(blinkerClass);
display[i].textContent = "Save Now";
}
clearInterval(intervalLoop);
}
}, 1000);
}
window.onload = function () {
var setMinutes = 60 * startTime,
display = $('#timer');
startTimer(setMinutes, display);
};
//End Countdown timer
Here is the CSS referenced in the code above
.done {color: tomato !important; font-weight: bold;}
.blink {
animation: blinker 1s step-start infinite;
}
#keyframes blinker {
50% {
opacity: 0;
}
}

Timer is not triggering after one minute using jQuery or give some other solution to trigger function after every 1 min?

var setTimer;
var isTimeSet = false;
if (!isTimeSet) {
setTimer = $('#hdn_timerTime').val();
isTimeSet = true;
}
initialTimer();
function initialTimer() {
var CustomMinutes = 60 * parseInt(setTimer),
display = $('#time');
startTimer(CustomMinutes, display);
}
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
$('#outputmeters').val(JSON.stringify(listItem));
// _hardMeter.UpdateMeterData();
_hardMeter.TempUpdateMeterDataConfirmation();
}
}, 1000);
}
This code I am using but for the first time it work fine than after that it time start reducing and function fire very quickly. I don't know how it happening.
Please help me out in this and if you have some better solution for it. Could you please share it?
You can use setInterval to call the same function repeatedly at set intervals until either the page is unloaded or you call clearInterval:
var timedFunction = function() {
... // Do something
}
setInterval(timedFunction, 60 * 1000);
If your timed function takes arguments which change each time, use setTimeout and call it within the function body as well
var timedFunctionWithArguments = function(iterations) {
console.debug(iterations); // Do something
setTimeout(timedFunctionWithArguments, 60 * 1000, iterations++);
}
timedFunctionWithArguments(0);

How to write a countdown timer in JavaScript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Just wanted to ask how to create the simplest possible countdown timer.
There'll be a sentence on the site saying:
"Registration closes in 05:00 minutes!"
So, what I want to do is to create a simple js countdown timer that goes from "05:00" to "00:00" and then resets to "05:00" once it ends.
I was going through some answers before, but they all seem too intense (Date objects, etc.) for what I want to do.
I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.
Demo with vanilla JavaScript
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<body>
<div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body>
Demo with jQuery
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 5,
display = $('#time');
startTimer(fiveMinutes, display);
});
However if you want a more accurate timer that is only slightly more complicated:
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<body>
<div>Registration closes in <span id="time"></span> minutes!</div>
</body>
Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"
Should a count down timer count down? Yes
Should a count down timer know how to display itself on the DOM? No
Should a count down timer know to restart itself when it reaches 0? No
Should a count down timer provide a way for a client to access how much time is left? Yes
So with these things in mind lets write a better (but still very simple) CountDownTimer
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.
An example that displays the time in XX:XX format and restarts after reaching 00:00
An example that displays the time in two different formats
An example that has two different timers and only one restarts
An example that starts the count down timer when a button is pressed
You can easily create a timer functionality by using setInterval.Below is the code which you can use it to create the timer.
http://jsfiddle.net/ayyadurai/GXzhZ/1/
window.onload = function() {
var minute = 5;
var sec = 60;
setInterval(function() {
document.getElementById("timer").innerHTML = minute + ":" + sec;
sec--;
if (sec == 00) {
minute--;
sec = 60;
if (minute == 0) {
minute = 5;
}
}
}, 1000);
}
Registration closes in <span id="timer">5:00</span>!
If you want a real timer you need to use the date object.
Calculate the difference.
Format your string.
window.onload=function(){
var start=Date.now(),r=document.getElementById('r');
(function f(){
var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
if(diff>3e5){
start=Date.now()
}
setTimeout(f,1e3);
})();
}
Example
Jsfiddle
not so precise timer
var time=5*60,r=document.getElementById('r'),tmp=time;
setInterval(function(){
var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
tmp!=0||(tmp=time);
},1000);
JsFiddle

Categories