How to create a JQuery Clock / Timer
You're looking for the setInterval
function, which runs a function every x milliseconds.
For example:
var start = new Date;
setInterval(function() {
$('.Timer').text((new Date - start) / 1000 + " Seconds");
}, 1000);
How to create a countdown timer with jQuery?
Try the following which will properly issue the count down for the selected values.
$(document).ready(function() {
// Function to update counters on all elements with class counter
var doUpdate = function() {
$('.countdown').each(function() {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
}
});
};
// Schedule the update to happen once every second
setInterval(doUpdate, 1000);
});
JSFiddle Example
- http://jsfiddle.net/n24BP/
Note: This will run the count down sequence on every element which has the countdown
class. If you'd like to make it more restrictive to a single element you'll need to alter the selector from .countdown
to something more restrictive. The easiest way is to add an id and reference the item directly.
<p id='theTarget'>15</p>
The JavaScript is a little more complex here because you'll want the timer to eventually shut off since there's not much chance, or use, of element with a duplicate id being added
$(document).ready(function() {
var timer = setInterval(function() {
var count = parseInt($('#theTarget').html());
if (count !== 0) {
$('#theTarget').html(count - 1);
} else {
clearInterval(timer);
}
}, 1000);
});
JSFiddle Example
- http://jsfiddle.net/bSe9E/
JavaScript Countdown Timer to specific time everyday
(function() { var start = new Date; start.setHours(23, 0, 0); // 11pm
function pad(num) { return ("0" + parseInt(num)).substr(-2); }
function tick() { var now = new Date; if (now > start) { // too late, go to tomorrow start.setDate(start.getDate() + 1); } var remain = ((start - now) / 1000); var hh = pad((remain / 60 / 60) % 60); var mm = pad((remain / 60) % 60); var ss = pad(remain % 60); document.getElementById('time').innerHTML = hh + ":" + mm + ":" + ss; setTimeout(tick, 1000); }
document.addEventListener('DOMContentLoaded', tick);})();
Only <span id='time'></span> left!
jQuery countdown timer for minutes and seconds
Move your timer2 declaration out of setInterval function, assign new value of time to timer2 at the end of execution to continue.
Working Snippet:
var timer2 = "5:01";var interval = setInterval(function() {
var timer = timer2.split(':'); //by parsing integer, I avoid all extra string processing var minutes = parseInt(timer[0], 10); var seconds = parseInt(timer[1], 10); --seconds; minutes = (seconds < 0) ? --minutes : minutes; if (minutes < 0) clearInterval(interval); seconds = (seconds < 0) ? 59 : seconds; seconds = (seconds < 10) ? '0' + seconds : seconds; //minutes = (minutes < 10) ? minutes : minutes; $('.countdown').html(minutes + ':' + seconds); timer2 = minutes + ':' + seconds;}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="countdown"></div>
Adding Time Buttons in JQuery Timer
Answer & Demo
So it turns out there isn't a legit way of doing this, truth be told there isn't a lot of documentation about the subject and the plugin itself doesn't provide such functionability, or at least not in a user friendly way.
But I went down to the guts of the code and managed to make it work.
Here is a JSFiddle where I demonstrate what I understood you wanted.
HTML
<div id="countdown"></div>
<button id="start">Start</button>
<button id="set60">Set 60s</button>
<button id="set120">Set 120s</button>
<button id="reset">Reset</button>
JavaScript
start = document.querySelector("#start");
set60 = document.querySelector("#set60");
set120 = document.querySelector("#set120");
reset = document.querySelector("#reset");
div = $("#countdown");
pingSound = new Audio("http://www.sounddogs.com/previews/2220/mp3/402763_SOUNDDOGS__mu.mp3");
pingSound.preload = "auto"; //<- Optional but recommended
countdown = div.countdown360({
radius: 50,
seconds: 30,
fontColor: '#FFFFFF',
autostart: false,
onComplete: function () {
pingSound.play();
}
});
countdown.start(); //This right here is for showing the clock on load.
countdown.stop();
start.onclick = function () {
startCountdown(countdown);
}
set60.onclick = function () {
setSeconds(countdown, 60);
}
set120.onclick = function () {
setSeconds(countdown, 120);
}
reset.onclick = function () {
setSeconds(countdown, 0);
}
function startCountdown(countdown) {
countdown.start();
}
function setSeconds(countdown, seconds) {
countdown.stop();
countdown.settings.seconds = seconds;
countdown.start();
}
Explanation
Variables
- start, set60, set120, reset : Link to their respective
button
elements. - div : Link to the countdown
div
element. - pingSound :
Audio
element that contains the "ping" sound. - countdown : The countdown object itself, you need to declare it like this, passing the initial properties and saving it in a variable.
Functions
- startCountdown(countdown) : Takes any countdown object and start's it's execution, this will get the countdown running.
- setSeconds(countdown,seconds) : Takes any countdown object and set's it second (it can be used in mid-excecution). It works by first stopping the countdown, then updating the
Countdown.settings.seconds
property, which is the actual seconds the countdown will run.
Development
With those variables & methods, how I did it is pretty straight forward.
If you want the clock hidden until you play it:
We first create the countdown object and hide the div.
div = $("#countdown");
div.css( "display" , "none" );
countdown = div.countdown360({..});
Why? Well because of how the plugin works. As soon as you create the countdown your div is made bigger by the plugin, and you need to create the countdown there because that's the only way it works, so if you don't want a blank square of nothing (since we haven't started the countdown) you have to hide the div itself.
So, we add an onclick
event to each button:
- for
start
->startCountdown(countdown) , div.css( "display" , "block" );
-> Starts the countdown and shows the div. - for
set60
->setSeconds(countdown,60)
-> Sets the countdown to 60s. - for
set120
->setSeconds(countdown,120)
-> Sets the countdown to 120s. - for
set0
->setSeconds(countdown,0)
-> Sets the countdown to 0s.
And that's it, it took me a while to figure out, hopefully I didn't just bore you to death, and may I suggest getting a better plugin next time? Good luck :)
If you want the clock displayed on load:
Okey, so this is an update upon your request, if we part from my original code, to make the div appear on load is quite simple (JSFiddle & code here have been updated)
We first create the countdown object, then start it and inmeadiatly stop it (freezing it until you start it again).
countdown = div.countdown360({..});
countdown.start();
countdown.stop();
Now, we add the same onclick
events to the buttons except for the start button, which will no longer have to display the div as block as it isn't hidden.
- for
start
->startCountdown(countdown)
-> Starts the countdown. - (..)
If you want to play a sound at the end of the countdown:
For the ping sound to play in the end, you just need to create a new Audio
object with the mp3/ogg src as a parameter:
pingSound = new Audio("http://www.sounddogs.com/previews/2220/mp3/402763_SOUNDDOGS__mu.mp3");
Then, preload the audio so it's ready to play (otherwise when you call play it will first have to load). This is optional but recommended.
pingSound.preload = "auto";
And then call the Audio.play()
function in the countdown's onComplete
event.
countdown = div.countdown360({
(..)
onComplete:function(){
pingSound.play();
}
});
That's it, happy coding :)
Updates
- Updated code to display the clock on load (1:43p.m 31/12/14)
- Updated code to play sound in the end of countdown(6:10p.m 02/01/14)
How Can I create A 5 second Countdown timer with jquery that ends with a login popup?
How about:
var counter = 0;
var interval = setInterval(function() {
counter++;
// Display 'counter' wherever you want to display it.
if (counter == 5) {
// Display a login box
clearInterval(interval);
}
}, 1000);
Countdown timer using jQuery or Google App Engine?
I created a timer using Javascript,But in that i used system time.
If that JavaScript really serves your needs, then that JavaScript code could easily be made dynamic as well. In the code, wherever the current system time is initialized, simply insert your server time using your language of choice (Python). In other words: use your server language (Python) to output the script just as it is right now, except for replacing the part that initializes the current time.
In PHP, some pseudocode (not sure about the arguments of the Date() constructor) might look like, for example:
// my_countdown_script.php
[..]
var startTime = new Date( <?php echo time(); ?> );
[..]
Then, rather than including your JavaScript, you would be including the PHP file that inserts the server time like above:
<script type="text/javascript" src="my_countdown_script.php"></script>
The good thing is: this will work in any browser that supports the JavaScript you already created.
(In some later version, your JavaScript could include some initializers that allow you to set the current time after including the library in your HTML. That would allow the actual JavaScript library to be static, and thus to be cached by the browser.)
Create Inrement Timer in Javascript
You can try something as simple as this:
var input = {year: 0, month: 0, day: 0, hours: 2, minutes: 10, seconds: 30};
var timestamp = new Date(input.year, input.month, input.day,
input.hours, input.minutes, input.seconds);
var interval = 1;
setInterval(function () {
timestamp = new Date(timestamp.getTime() + interval * 1000);
$('.countdown2').text(timestamp.getDay()+'d:'+timestamp.getHours()+'h:'+
timestamp.getMinutes()+'m:'+timestamp.getSeconds()+'s');
}, Math.abs(interval) * 1000);
Each interval, you're incrementing the time value of a Date object, then reading the hours/minutes/seconds back out and letting the native Date implementation worry about the conversion from raw seconds. Interval can be positive or negative, and as large as you like.
Demo
Related Topics
Jquery, Find Div Class Name at a Certain Position While Scrolling
Remembering State Before App Goes in Foreground
Can Any Desktop Browsers Detect When the Computer Resumes from Sleep
.Append(), Prepend(), .After() and .Before()
Jquery Add Required to Input Fields
Setting Div Width and Height in JavaScript
How to Replace the Entire HTML Node Using Jquery
What's the Yield Keyword in JavaScript
Where Would I Use a Bitwise Operator in JavaScript
Get the Visible Height of a Div with Jquery
How to Reverse an Array in JavaScript Without Using Libraries
Why Can't We Have Return in the Ternary Operator
What Does Document.Domain = Document.Domain Do
Google Chromecast Sender Error If Chromecast Extension Is Not Installed or Using Incognito