Making countdown function in jQuery
-
09-12-2019 - |
Question
I am newbie and need ur help. I have a problem on finding out days, hours, minutes and seconds. I dont know what to update minutes after seconds will reach 60 and same with hours and days.
I am trying to countdown to a given date in a format of Days/Hours/Minutes/Seconds.
Here is the link of what I've done so far.
Thnx in advance! :)
Solution
I've modified your count_execution
function and added some comments. It should do what you ask.
function count_execution() {
// target date of event
var eventDate = new Date(settings.date);
// now
var currentDate = new Date();
// get date diff *in milliseconds*
var diff = Math.abs(currentDate - eventDate);
// compute days left
// 24h * 60m * 60s * 1000 = 86400000
var days = Math.floor(diff / 86400000);
diff = diff % 86400000;
// compute hours left
// 60m * 60s * 1000 = 3600000
var hours = Math.floor(diff / 3600000);
diff = diff % 3600000;
// the same for minutes
var minutes = Math.floor(diff / 60000);
diff = diff % 60000;
// finally, seconds
var seconds = Math.floor(diff / 1000);
$this.find('#days').text(days);
$this.find('#hours').text(hours);
$this.find('#mins').text(minutes);
$this.find('#secs').text(seconds);
}
Hope it helps.
OTHER TIPS
var seconds = 1355998990 - new Date().getTime(), // whatever
minutes = Math.floor(seconds/60),
hours = Math.floor(minutes/60),
days = Math.floor(hours/24);
seconds %= 60;
minutes %= 60;
hours %= 24;
console.log("d: " + days + " h: " + hours + " m: " + minutes + " s: " + seconds);
Will this do?
Also make sure to check out this; maybe you can get some inspiration there.
why don't you use one of the many plugins available to do the trick, consider the following links:
http://keith-wood.name/countdown.html
this one is listing many plugins for the same purpose, use any of them and smile :) http://www.tripwiremagazine.com/2012/01/jquery-countdown-scripts.html