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
Related
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;
}
}
I am making a riddle, where the people who try to solve it have 45 minutes to solve the riddle, and when they don't answer correctly, I want the timer to go down five minutes, to prevent them from just guessing the answers. How could I do it, I am very new to using javascript, this is the first time I'm working with it.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
var cat1 = ($("input[#name=Verdachte]:checked").val() != "2");
var cat2 = ($("input[#name=Moordwapen]:checked").val() != "4");
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
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) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fortyfiveMinutes = 60 * 45,
display = document.querySelector('#time');
startTimer(fortyfiveMinutes,display);}
I want the timer to go down five minutes when cat1 is true, and/or when cat2 is true.
Inside of timer, just check the input, and if it is true, disable the input and increase the time:
var cat1 = $("input[#name=Verdachte]:checked");
if(cat1.val() === "2") {
cat1.val("you are right :)");
cat1.attr("disabled", true);
start -= 1000 * 60 * 5;
}
//...
... that would be even more elegant with event handlers ...
I'm trying to create a timer for 30 seconds and i'm looking to do this on my own, however I seem to be stuck here:
var Starttime = ( needs to be 30 seconds )
var Timeleft = Starttime - 1
if (Timeleft === 0) {
console.log("TIMER FINISHED BEEP BOOP");
}
and through lots of research still not able to find how to declare variable as a simple 30 seconds of time, and I am aware that I would need to do the same for the 1 ( change it to 1 second). TL;DR how do I write 30 seconds
try this function using setinterval() :
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 () {
//this is where you can modifies the time amount.
var minutes= 60 ,
display = document.querySelector('#time');
startTimer(minutes, display);
};
<body>
<div>One minute countdown <span id="time">1:00</span> minutes!</div>
</body>
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.
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);