Javascript countdown to get current interval time running - javascript

I have countdown function using Javascript/jQuery.
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = days + 'days ' + hours + 'hrs ' + minutes + 'mins ' + seconds + 'seconds ';
target.html(timestring)
if (dist > 0) {
setTimeout(timer, 1000);
} else {
callback()
}
})()
}
// 10 seconds into the future
var time = "08/02/2021 17:05:00";
var time2 = "08/02/2021 17:33:00";
// countdown function call
countdownto($('#countdown'), time, function(){
console.log('tadaaa')
countdownto($('#countdown2'), time2, function(){
console.log('tadaaa')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="countdown"></div>
<div id="countdown2"></div>
Now I need to add function interval second there to get the current interval time.
My question is: how to get interval time inside this function:
countdownto($('#countdown'), time, function(){
console.log('tadaaa')
alert(time); // <-- how to get interval time? Alert not appear, as I know here when the countdown finish.
countdownto($('#countdown2'), time2, function(){
console.log('tadaaa')
})
})

Technically, you already have the time as string inside your global time variable. If you want to pass it to the callback anyway, you have to pass it where the callback is invoked:
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = days + 'days ' + hours + 'hrs ' + minutes + 'mins ' + seconds + 'seconds ';
target.html(timestring)
if (dist > 0) {
setTimeout(timer, 1000);
} else {
callback(finish)
}
})()
}
// 10 seconds into the future
var time = "08/02/2021 17:05:00";
var time2 = "08/02/2021 17:33:00";
// countdown function call
countdownto($('#countdown'), time, function(time){
console.log('tadaaa')
alert(time); // <-- how to get interval time? Alert not appear, as I know here when the countdown finish.
countdownto($('#countdown2'), time2, function(){
console.log('tadaaa')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="countdown"></div>
<div id="countdown2"></div>

Related

Make Countdown Timer 2 Digits For HH:MM:SS [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 2 years ago.
So, I am a novice in Javascript and I am wondering if someone can help me with this. I believe this question is really really easy for most. Well, this is a countdown timer with select options to set up the time. It is working well. The problem is that, when the countdown starts, I want the single digit numbers to show the number zero first. Basically, I want the numbers for HH:MM:SS to be 2 digits. For example, 00:01:59 and not 0:1:59. I believe it has something to do with padString or something (I could be wrong), but my proficiency is still no that advanced.
Note: I would highly appreciate it if we can come up with a Vanilla Javascript solution and not JQuery simply because I want to use this offline and without any online dependencies. Thank you in advance.
Javascript
<script>
var hours = 0;
var minutes = 0;
var seconds = 0;
var interval = null;
document.getElementById('hours').addEventListener('change', e => {
hours = +e.target.value;
});
document.getElementById('minutes').addEventListener('change', e => {
minutes = +e.target.value;
});
document.getElementById('seconds').addEventListener('change', e => {
seconds = +e.target.value;
});
document.getElementById('startTimer').addEventListener('click', () => {
var timeInSeconds = (hours * 60 * 60) +
(minutes * 60) +
seconds;
const audio = new Audio("audioURL.mp3");
var displayTime = () => {
var displayHours = Math.floor(timeInSeconds / (60 * 60));
var remainder = timeInSeconds - (displayHours * 60 * 60);
var displayMinutes = Math.floor(remainder / 60);
var displaySeconds = remainder - (displayMinutes * 60);
document.getElementById("timer").innerHTML = displayHours + ":" +
displayMinutes + ":" + displaySeconds;
};
interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
clearInterval(interval);
audio.play();
}
}, 1000);
});
</script>
You could use ('0' + myValue).substr(-2) to fix the length with 2 characters. In this case '01' would be stay as '01' and '012' will be '12' because the -2 will cut the string from the end. Then your code will be:
var hours = 00;
var minutes = 00;
var seconds = 00;
var interval = null;
document.getElementById('hours').addEventListener('change', e => {
hours = +e.target.value;
});
document.getElementById('minutes').addEventListener('change', e => {
minutes = +e.target.value;
});
document.getElementById('seconds').addEventListener('change', e => {
seconds = +e.target.value;
});
document.getElementById('startTimer').addEventListener('click', () => {
var timeInSeconds = (hours * 60 * 60) +
(minutes * 60) +
seconds;
const audio = new Audio("audioURL.mp3");
var displayTime = () => {
var displayHours = Math.floor(timeInSeconds / (60 * 60));
var remainder = timeInSeconds - (displayHours * 60 * 60);
var displayMinutes = Math.floor(remainder / 60);
var displaySeconds = remainder - (displayMinutes * 60);
document.getElementById("timer").innerHTML = ('0' + displayHours).substr(-2) + ":" +
('0' + displayMinutes).substr(-2) + ":" + ('0' + displaySeconds).substr(-2);
};
interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
clearInterval(interval);
audio.play();
}
}, 1000);
});

JavaScript Countdown Timer to specific time everyday

I am currently developing a website with a countdown timer at the headline: http://iphone.myhandykey.com/
The current timer is just 12hrs + few mins.. What I would like is the countdown timer will show the time remaining until 11PM on the Time Zone of the current visitor. Is that possible? Thanks!
Here is the JavaScript:
function startTimer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {
hours = parseInt(((timer / 60) / 60 ) % 60, 10);
minutes = parseInt((timer / 60)%60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var onehour = 60 * 600 * 1.231,
display = document.querySelector('#time');
startTimer(onehour, display);
};
Here is the HTML:
<span id=time></span>
EDIT: If the visitor's current time is for example 11:40pm, It should display 23hrs & 20mins left..
(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!
Something like this:
$(document).ready(function () {
var mg = new Date(2016, 5, 21, 0, 0, 0, 0);
var tmr = window.setInterval(function () {
var d = new Date();
var dif = mg - d;
var s = parseInt(dif / 1000);
if (s < 0) {
document.getElementById('spCnt').innerHTML = 'Event starts';
window.clearInterval(tmr);
return;
}
var sec = s % 60;
var m = parseInt(s / 60);
var min = m % 60;
var h = parseInt(m / 60);
var hour = h % 24;
d = parseInt(h / 24);
document.getElementById('spCnt').innerHTML = d + ' days ' + hour + ' hours ' + min + ' min and ' + sec + ' sec remaining';
}, 1000);
});

My javascriptcode is working when i put alert.I need to Display time in Counter Format(Seconds decreasing way)

My javascriptcode is working fine when i put alert.I need to Display time in Counter Format(Second decreasing way). Please help me in resolving this issue
<script type="text/javascript">
window.onload = function () {
//alert("request>>>");
var count = 0;
var start_actual_time = document.getElementById("timerStartTime").value;
var end_actual_time = document.getElementById("timerEndTime").value;
start_actual_time = new Date(start_actual_time);
var start_actual_time1 = new Date(start_actual_time.getTime());
start_actual_time1 = new Date(start_actual_time1);
var end_actual_time1 = new Date(end_actual_time);
var hours =end_actual_time1.getHours()- start_actual_time1.getHours();
var minutes = end_actual_time1.getMinutes() - start_actual_time1.getMinutes();
var seconds = end_actual_time1.getSeconds()- start_actual_time1.getSeconds();
seconds = hours * 3600 + minutes * 60 + seconds;
//alert ("seconds >>." +seconds);
timer(seconds);
};
function timer(seconds) {
alert("calling timer");
var s1 = Number(seconds);
var hours = Math.floor(s1 / 3600);
var minutes = Math.floor(s1 % 3600 / 60);
var s = Math.floor(s1 % 3600 % 60);
//alert("sec1" + s);
display = document.querySelector('#time');
var formatted = ((hours < 10)?("0" + hours):hours) + ":" + ((minutes < 10)?("0" + minutes):minutes) + ":" + ((s < 10)?("0" + s):s)
display.textContent = formatted ;
seconds = seconds - 1;
timer(seconds);
}
</script>
The way your code is written creates a
too much recursion
exception for me.
Therefore I have avoided recursive invokes and used javascript setInterval:
var refreshIntervalId = setInterval(function(){ timer(); }, 1000);
When your seconds reach zero, timer is stopped:
if (seconds == -1){
clearInterval(refreshIntervalId);
Link to working fiddle: http://jsfiddle.net/3ggspruf/2/

Website Countdown js

Hi I am having a hard time making this countdown work for me. I am trying to make it count down to every sunday at 11:15am since that is when our church service starts. Can anyone pleaes help me? I have the code here.
function croAnim(){
// IF THERE'S A COUNTDOWN
if ($('ul.cro_timervalue').length !== 0) {
// GET ALL THE INSTANCES OF THE TIMER
$('ul.cro_timervalue').each(function() {
var $this = $(this),
timesets = $this.data('cro-countdownvalue'),
now = new Date(),
tset = Math.floor(now / 1000),
counter1 = timesets - tset;
// CALCULATE SECONDS
var seconds1 = Math.floor(counter1 % 60);
seconds1 = (seconds1 < 10 && seconds1 >= 0) ? '0'+ seconds1 : seconds1;
// CALCULATE MINUTES
counter1 =counter1/60;
var minutes1 =Math.floor(counter1 % 60);
minutes1 = (minutes1 < 10 && minutes1 >= 0) ? '0'+ minutes1 : minutes1;
// CALCULATE HOURS
counter1=counter1/60;
var hours1=Math.floor(counter1 % 24);
hours1 = (hours1 < 10 && hours1 >= 0) ? '0'+ hours1 : hours1;
// CALCULATE DAYS
counter1 =counter1/24;
var days1 =Math.floor(counter1);
days1 = (days1 < 10 && days1 >= 0) ? '0'+ days1 : days1;
// ADD THE VALUES TO THE CORRECT DIVS
$this.find('span.secondnumber').html(seconds1);
$this.find('span.minutenumber').html(minutes1);
$this.find('span.hournumber').html(hours1);
$this.find('span.daynumber').html(days1);
});
}
}
// CREATE A INTERVAL FOR THE TIMER
croInit = setInterval(croAnim, 100);
I answered a similar question about a week or so ago. I have a really simple countdown function already written. The trick is to modify it to get the next Sunday # 11:15 am, which I've written a function for.
var getNextSunday = function () {
var today = new Date(),
day = today.getDay(), // 1 for Mon, 2 for Tue, 3 for Wed, etc.
delta = 7 - day;
var sunday = new Date(today.getTime() + (delta * 24 * 3600 * 1000));
sunday.setHours(11);
sunday.setMinutes(15);
sunday.setSeconds(0);
return sunday;
}
var t = getNextSunday(),
p = document.getElementById("time"),
timer;
var u = function () {
var delta = t - new Date(),
d = delta / (24 * 3600 * 1000) | 0,
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0,
m = (delta %= 3600 * 1000) / (60 * 1000) | 0,
s = (delta %= 60 * 1000) / 1000 | 0;
if (delta < 0) {
clearInterval(timer);
p.innerHTML = "timer's finished!";
} else {
p.innerHTML = d + "d " + h + "h " + m + "m " + s + "s";
}
}
timer = setInterval(u, 1000);
<h1 id="time"></h1>
This should be easy enough to adapt to fit your website's needs. The only tricky part might be my use of
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0
delta %= ... returns delta, after performing the %=. This was just to save characters. If you don't like this, you can just separate the delta %= ... part:
delta %= 24 * 3600 * 1000;
h = delta / (3600 * 1000) | 0;
// ... do the same for the rest
This object uses a few semi-advanced javascript ideas (closures and * IIFE*) so hopefully it is easy-ish to understand. If you have any questions feel free to leave a comment.
var churchtime = (function (){
// Total seconds passed in the week by sunday 11:15am
var magic_number = 558900;
var now;
var rawtime = function (){
//updates now with the current date and time
now = new Date()
//Converts now into pure seconds
return (((((((now.getDay()-1)*24)+now.getHours())*60)+now.getMinutes())*60)+now.getSeconds());
};
//closure
return {
raw_countdown : function (){
return Math.abs(rawtime()-magic_number);
},
countdown : function(){
var time = Math.abs(rawtime()-magic_number)
var seconds = time % 60, time = (time - seconds)/60;
var minutes = time % 60, time = (time - minutes)/60;
var hours = time % 24, time = (time - hours)/24;
var days = time;
return [days,hours,minutes,seconds];
}
}
})(558900); //<- Total seconds passed in the week by sunday 11:15am
churchtime.raw_countdown()// returns the raw number of seconds until church
churchtime.countdown() // returns an array of time until church [days,hours,minutes,seconds]
Once you have an object like churchtime, it should be super easy to implement.
For example:
var churchtime = (function(magic_number) {
var now;
var rawtime = function() {
//updates now with the current date and time
now = new Date()
//Converts now into pure seconds
return (((((((now.getDay() - 1) * 24) + now.getHours()) * 60) + now.getMinutes()) * 60) + now.getSeconds());
};
//closure
return {
raw_countdown: function() {
return Math.abs(rawtime() - magic_number);
},
countdown: function() {
var time = Math.abs(rawtime() - magic_number)
var seconds = time % 60,
time = (time - seconds) / 60;
var minutes = time % 60,
time = (time - minutes) / 60;
var hours = time % 24,
time = (time - hours) / 24;
var days = time;
return [days, hours, minutes, seconds];
}
}
})(); //<- IIFE
AutoUpdate = function AutoUpdate() {
var time = churchtime.countdown();
document.getElementById("day").innerHTML = time[0];
document.getElementById("hour").innerHTML = time[1];
document.getElementById("min").innerHTML = time[2];
document.getElementById("sec").innerHTML = time[3];
setTimeout(AutoUpdate, 900); //Calls it's self again after .9 seconds
}(); //<- IIFE
<h1>Day:<span id="day"></span> Hour:<span id="hour"></span>
Minute:<span id="min"></span> second: <span id="sec"></span></h1>

Countup since a specific date in javascript/jQuery [duplicate]

I want to use a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. No milliseconds. How can it be coded?
var count=30;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
//counter ended, do something here
return;
}
//Do code for showing the number of seconds here
}
To make the code for the timer appear in a paragraph (or anywhere else on the page), just put the line:
<span id="timer"></span>
where you want the seconds to appear. Then insert the following line in your timer() function, so it looks like this:
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}
I wrote this script some time ago:
Usage:
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
So far the answers seem to rely on code being run instantly. If you set a timer for 1000ms, it will actually be around 1008 instead.
Here is how you should do it:
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},100); // the smaller this number, the more accurate the timer will be
}
To use, call:
timer(
5000, // milliseconds
function(timeleft) { // called every step to update the visible countdown
document.getElementById('timer').innerHTML = timeleft+" second(s)";
},
function() { // what to do after
alert("Timer complete!");
}
);
Here is another one if anyone needs one for minutes and seconds:
var mins = 10; //Set the number of minutes you need
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
/*
* The following line has been commented out due to a suggestion left in the comments. The line below it has not been tested.
* setTimeout('Decrement()',1000);
*/
setTimeout(Decrement,1000);
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if(secs !== -1) setTimeout('Decrement()',1000);
}
// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Sep 29 2007 00:00:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);
function update() {
now = new Date();
seconds = (theevent - now) / 1000;
seconds = Math.round(seconds);
minutes = seconds / 60;
minutes = Math.round(minutes);
hours = minutes / 60;
hours = Math.round(hours);
days = hours / 24;
days = Math.round(days);
document.form1.days.value = days;
document.form1.hours.value = hours;
document.form1.minutes.value = minutes;
document.form1.seconds.value = seconds;
ID = window.setTimeout("update();", 1000);
}
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
<p>Days
<input type="text" name="days" value="0" size="3">Hours
<input type="text" name="hours" value="0" size="4">Minutes
<input type="text" name="minutes" value="0" size="7">Seconds
<input type="text" name="seconds" value="0" size="7">
</p>
</form>
Just modified #ClickUpvote's answer:
You can use IIFE (Immediately Invoked Function Expression) and recursion to make it a little bit more easier:
var i = 5; //set the countdown
(function timer(){
if (--i < 0) return;
setTimeout(function(){
console.log(i + ' secs'); //do stuff here
timer();
}, 1000);
})();
var i = 5;
(function timer(){
if (--i < 0) return;
setTimeout(function(){
document.getElementsByTagName('h1')[0].innerHTML = i + ' secs';
timer();
}, 1000);
})();
<h1>5 secs</h1>
Expanding upon the accepted answer, your machine going to sleep, etc. may delay the timer from working. You can get a true time, at the cost of a little processing. This will give a true time left.
<span id="timer"></span>
<script>
var now = new Date();
var timeup = now.setSeconds(now.getSeconds() + 30);
//var timeup = now.setHours(now.getHours() + 1);
var counter = setInterval(timer, 1000);
function timer() {
now = new Date();
count = Math.round((timeup - now)/1000);
if (now > timeup) {
window.location = "/logout"; //or somethin'
clearInterval(counter);
return;
}
var seconds = Math.floor((count%60));
var minutes = Math.floor((count/60) % 60);
document.getElementById("timer").innerHTML = minutes + ":" + seconds;
}
</script>
For the sake of performances, we can now safely use requestAnimationFrame for fast looping, instead of setInterval/setTimeout.
When using setInterval/setTimeout, if a loop task is taking more time than the interval, the browser will simply extend the interval loop, to continue the full rendering. This is creating issues. After minutes of setInterval/setTimeout overload, this can freeze the tab, the browser or the whole computer.
Internet devices have a wide range of performances, so it's quite impossible to hardcode a fixed interval time in milliseconds!
Using the Date object, to compare the start Date Epoch and the current. This is way faster than everything else, the browser will take care of everything, at a steady 60FPS (1000 / 60 = 16.66ms by frame) -a quarter of an eye blink- and if the task in the loop is requiring more than that, the browser will drop some repaints.
This allow a margin before our eyes are noticing (Human = 24FPS => 1000 / 24 = 41.66ms by frame = fluid animation!)
https://caniuse.com/#search=requestAnimationFrame
/* Seconds to (STRING)HH:MM:SS.MS ------------------------*/
/* This time format is compatible with FFMPEG ------------*/
function secToTimer(sec){
const o = new Date(0), p = new Date(sec * 1000)
return new Date(p.getTime()-o.getTime()).toString().split(" ")[4] + "." + p.getMilliseconds()
}
/* Countdown loop ----------------------------------------*/
let job, origin = new Date().getTime()
const timer = () => {
job = requestAnimationFrame(timer)
OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
}
/* Start looping -----------------------------------------*/
requestAnimationFrame(timer)
/* Stop looping ------------------------------------------*/
// cancelAnimationFrame(job)
/* Reset the start date ----------------------------------*/
// origin = new Date().getTime()
span {font-size:4rem}
<span id="OUT"></span>
<br>
<button onclick="origin = new Date().getTime()">RESET</button>
<button onclick="requestAnimationFrame(timer)">RESTART</button>
<button onclick="cancelAnimationFrame(job)">STOP</button>
You can do as follows with pure JS. You just need to provide the function with the number of seconds and it will do the rest.
var insertZero = n => n < 10 ? "0"+n : ""+n,
displayTime = n => n ? time.textContent = insertZero(~~(n/3600)%3600) + ":" +
insertZero(~~(n/60)%60) + ":" +
insertZero(n%60)
: time.textContent = "IGNITION..!",
countDownFrom = n => (displayTime(n), setTimeout(_ => n ? sid = countDownFrom(--n)
: displayTime(n), 1000)),
sid;
countDownFrom(3610);
setTimeout(_ => clearTimeout(sid),20005);
<div id="time"></div>
Based on the solution presented by #Layton Everson I developed a counter including hours, minutes and seconds:
var initialSecs = 86400;
var currentSecs = initialSecs;
setTimeout(decrement,1000);
function decrement() {
var displayedSecs = currentSecs % 60;
var displayedMin = Math.floor(currentSecs / 60) % 60;
var displayedHrs = Math.floor(currentSecs / 60 /60);
if(displayedMin <= 9) displayedMin = "0" + displayedMin;
if(displayedSecs <= 9) displayedSecs = "0" + displayedSecs;
currentSecs--;
document.getElementById("timerText").innerHTML = displayedHrs + ":" + displayedMin + ":" + displayedSecs;
if(currentSecs !== -1) setTimeout(decrement,1000);
}
// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Nov 13 2017 22:05:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);
function update() {
now = new Date();
seconds = (theevent - now) / 1000;
seconds = Math.round(seconds);
minutes = seconds / 60;
minutes = Math.round(minutes);
hours = minutes / 60;
hours = Math.round(hours);
days = hours / 24;
days = Math.round(days);
document.form1.days.value = days;
document.form1.hours.value = hours;
document.form1.minutes.value = minutes;
document.form1.seconds.value = seconds;
ID = window.setTimeout("update();", 1000);
}
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
<p>Days
<input type="text" name="days" value="0" size="3">Hours
<input type="text" name="hours" value="0" size="4">Minutes
<input type="text" name="minutes" value="0" size="7">Seconds
<input type="text" name="seconds" value="0" size="7">
</p>
</form>
My solution works with MySQL date time formats and provides a callback function. on complition.
Disclaimer: works only with minutes and seconds, as this is what I needed.
jQuery.fn.countDownTimer = function(futureDate, callback){
if(!futureDate){
throw 'Invalid date!';
}
var currentTs = +new Date();
var futureDateTs = +new Date(futureDate);
if(futureDateTs <= currentTs){
throw 'Invalid date!';
}
var diff = Math.round((futureDateTs - currentTs) / 1000);
var that = this;
(function countdownLoop(){
// Get hours/minutes from timestamp
var m = Math.floor(diff % 3600 / 60);
var s = Math.floor(diff % 3600 % 60);
var text = zeroPad(m, 2) + ':' + zeroPad(s, 2);
$(that).text(text);
if(diff <= 0){
typeof callback === 'function' ? callback.call(that) : void(0);
return;
}
diff--;
setTimeout(countdownLoop, 1000);
})();
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
}
// $('.heading').countDownTimer('2018-04-02 16:00:59', function(){ // on complete})
var hr = 0;
var min = 0;
var sec = 0;
var count = 0;
var flag = false;
function start(){
flag = true;
stopwatch();
}
function stop(){
flag = false;
}
function reset(){
flag = false;
hr = 0;
min = 0;
sec = 0;
count = 0;
document.getElementById("hr").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("count").innerHTML = "00";
}
function stopwatch(){
if(flag == true){
count = count + 1;
setTimeout( 'stopwatch()', 10);
if(count ==100){
count =0;
sec = sec +1;
}
}
if(sec ==60){
min = min +1 ;
sec = 0;
}
if(min == 60){
hr = hr +1 ;
min = 0;
sec = 0;
}
var hrs = hr;
var mins = min;
var secs = sec;
if(hr<10){
hrs ="0" + hr;
}
if(min<10){
mins ="0" + min;
}
if(sec<10){
secs ="0" + sec;
}
document.getElementById("hr").innerHTML = hrs;
document.getElementById("min").innerHTML = mins;
document.getElementById("sec").innerHTML = secs;
document.getElementById("count").innerHTML = count;
}

Categories

Resources