Javascript Countdown Timer for every other Tuesday - javascript

I run the site for a radio show that airs every other Tuesday from 6 to 7am.
I'm trying to make a Javascript that will countdown the days, hours, minutes, and seconds till our show is live.
Then, when our show is live, I'd like to replace the countdown timer with an image using PHP. One hour later at 7am, our show is over; then I'd like the PHP script to return to the countdown timer.
I've tried to search around for countdown scripts that auto-update, but haven't found anything so far.
How would I make these scripts?

About a few hours ago i finished developing a javascript timer.
It should do the trick.
function miniTimer(s,callback,opt){
function getParam(value,defaultValue){
return typeof value == 'undefined' ? defaultValue : value;
}
this.s = getParam(s,0);
this.callback = getParam(callback,null);// a callback function that takes the current time in seconds as the first parameter and the formated time as the second
var opt = getParam(opt,{});
this.settings = {
masterCallback : getParam(opt.masterCallback,null),// same as above, but this one is called when the miniTimer finishes it's work (if maxPaceDuration or limitValue is set)
autoplay : getParam(opt.autoplay,false),
limitValue : getParam(opt.limitValue,null),
maxPaceCount : getParam(opt.maxPaceCount,null),
paceDuration : getParam(opt.paceDuration,1000),//milisec,
paceValue : getParam(opt.paceValue,1)//increment with only one second; set to -1 to countdown
};
this.interval = 0;
this.paceCount = 0;
if(this.settings.autoplay)
this.start();
return this;
}
miniTimer.prototype = {
toString : function(){
var d = Math.floor(this.s / (24 * 3600));
var h = Math.floor((this.s - d* 24 * 3600) / 3600);
var m = Math.floor((this.s - d* 24 * 3600 - h * 3600) / 60);
var s = this.s % 60;
if(h <= 9 && h >= 0)
h = "0"+h;
if(m <= 9 && m >= 0)
m = "0"+m;
if(s <= 9 && s >= 0)
s = "0"+s;
var day = d != 1 ? "days" : "day";
return d+" "+day+" "+h+":"+m+":"+s;
},
nextPace : function(){
if((this.settings.maxPaceCount != null && this.settings.maxPaceCount <= this.paceCount)
|| (this.settings.limitValue != null && this.settings.limitValue == this.s))
{
this.stop();
if(this.settings.masterCallback != null)
this.settings.masterCallback(this.s,this.toString());
return;
}
this.paceCount++;
var aux = this.s + this.settings.paceValue;
this.s += this.settings.paceValue;
if(this.callback != null)
this.callback(this.s,this.toString());
return this;
},
start : function(){
var $this = this;
this.interval = setInterval(function(){$this.nextPace();},this.settings.paceDuration);
return this;
},
stop : function(){
clearInterval(this.interval);
return this;
}
}
Now all you have to do is configure the proper callback function:
var el = document.getElementById('timer');
function getNextTuesday(){
var nextTuesday = new Date();
var t = nextTuesday.getDay();
t = t > 2 ? 9 - t : 2 - t;
nextTuesday.setDate(nextTuesday.getDate() + t);
return nextTuesday;
}
var showDuration = 2 * 60 * 60;//2h
var t = new miniTimer(Math.floor((getNextTuesday() - new Date())/1000),function(date,string){
if(date > 0)
el.innerHTML = string;
else
{
if(date <= -showDuration)
t.s = Math.floor((getNextTuesday() - new Date())/1000);
el.innerHTML = "<img src='http://t2.gstatic.com/images?q=tbn:ANd9GcT3CEVtaAYQJ4ALZRmgMHsCA8CG5tdpauLqSMhB66HJP_A0EDPPXw'>";
}
},{autoplay:true,paceValue : -1});
here's a working example : http://jsfiddle.net/gion_13/8wxLP/1/

You'll need to find the GMT time for 7am on the first tuesday the show is on,
and use new Date on the client to convert it to the user's local time.
Once you do that, it is like any other count down.
This example assumes EDT and April 5 for the first show.
(Date.UTC(2011, 3, 5, 11))
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<script>
function counttoShow(){
var A= [], x, d, diff,cd=document.getElementById('countdown'),
cdimg=document.getElementById('onAir'),
onair= new Date(Date.UTC(2011, 3, 5, 11)), now= new Date();
while(onair<now) onair.setDate(onair.getDate()+14);
diff= (onair-now);
if(diff<3600000){
cdimg.style.visibility='visible';
cd.style.visibility='hidden';
}
else{
x= Math.abs(diff-3600000);
d= Math.floor(x/86400000);
if(d> 1){
A.push( d + " days");
x%= 86400000;
}
x= Math.floor(x/1000);
if(x> 3600){
d= Math.floor(x/3600);
A.push(d + " hour" +(d> 1? "s": ""));
x%= 3600;
}
if(x> 60){
d= Math.floor(x/60);
A.push(d + " minute" +(d> 1? "s": ""));
x%= 60;
}
if(x> 0) A.push(x + " second" +(x> 1? "s": ""));
cdimg.style.visibility='hidden';
cd.value= A.join(", ");
}
}
window.onload=function(){
var cdtimer=setInterval(counttoShow,1000);
document.body.ondblclick=function(){
if(cd.timer){
clearInterval(cdtimer);
cdtimer=null;
}
else cdtimer=setInterval(counttoShow,1000);
}
}
</script>
</head>
<body>
<h1>Radio Show</h1>
<p><img id="onAir" src="onair.gif">
<input id="countdown" type="text" size="40" readOnly style="border:none"> until show time.
</p>
</div>
</body>
</html>

This will get you the number of seconds until your next show (assuming your next show is tomorrow). Then you need to find the time from there.
var now = new Date(),
then = new Date( 2011, 3, 9 ),
diff = new Date();
diff.setTime( Math.abs( then.getTime() - now.getTime() ) );
diff.getTime();
From that point, you can set a timeout to run every second to recude the number of seconds displayed by 1, for example.
setTimeout( reduceSeconds );

Related

How do I stop my countdown timer from executing after it has reached the deadline on refresh of my browser

This is how the JavaScript looks like. I tried searching for solutions but couldn't find. Please I need detailed solutions. Online I kept seeing cookies but I don't know how to use it in this case.
function countDown() {
var now = new Date();
var eventDate = new Date(2020, 5, 22);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h: h;
m = (m < 10) ? "0" + m: m;
s = (s < 10) ? "0" + s: s;
document.getElementById("days").textContent = d;
document.getElementById("days").innerText = d;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
var t = setTimeout(countDown, 1000);
if (d == 0 && h == 0 && m == 0 && s == 0) {
clearTimeout(t);
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
}
countDown();
</script>
The trouble with your code is in the date checking logic.
Checking with == will only give you a truthy response if the datetime (or part thereof) is the same as the value you're checking it against.
However, you need to check whether the date is already past. To do this, you need to use a < or <= operator.
Here's an example of what I mean. The info is console.loged instead, you can re-implement the DOM editing you have in your question.
function countDown() {
var now = new Date();
var eventDate = new Date(2020, 4, 22); // 22 May 2020
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h: h;
m = (m < 10) ? "0" + m: m;
s = (s < 10) ? "0" + s: s;
var t = setTimeout(countDown, 1000);
// This if statement only runs exactly on eventDate
if (d == 0 && h == 0 && m == 0 && s == 0) {
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
// This if statement will run if we're past or exactly on eventDate
if (remTime <= 0) {
clearTimeout(t);
}
// This console.log shows that the numbers become negative after the date
console.log(remTime, d,h,m,s);
}
countDown();

PHP Time Difference Not Working

UPDATE
Thanks to Mike C for the help. The database was structured under EndTime instead of endTime.
--
I know this may be asked several times - I have read several tutorials and I get errors. Would love some help!
I have two times in a MySQL database. I'm trying to take the time difference from time2 to time1 to display to the client in hours:minutes:seconds format. Both times in the database are DateTime format.
I have a Live Timer (taking time1 from server time) that displays in the web page if the closingTime variable isn't complete. The If statement works fine. Once we have a Time1 and Time2 time established on the page the page will load a time but it's the current snapshot of the StartTime difference from the server time.
In the picture above, the left is a live javascript timer and the right is just taking a snapshot instead of displaying the time difference between startTime and COGtime
Variables: (from DateTime in MySQL)
$startTime = $row['startTime'];
$COGTime = $row['endTime'];
If only startTime is entered: (Working time on left side of image)
echo '<div id="StartTimeFromServer"></div>';
If both StartTime and endTime are entered: (BROKEN: currently right side of image.. should take COGTime - startTime)
$date_a = new DateTime($startTime);
$date_b = new DateTime($COGTime);
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
Counter JS Script
<script type="text/javascript">
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.updateNumOfDays();
this.updateCounter();
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
var self = this;
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML ="" + this.hours + "" + (this.hours == 1? ":" : ":") + "" +
"" + this.minutes + "" + (this.minutes == 1? ":" : ":") + "" +
"" + this.seconds + "" + (this.seconds == 1? "" : "") + "";
var self = this;
setTimeout(function(){self.updateCounter();}, 1000);
}
window.onload=function(){
new CountUp('<?php echo $startTime // downtime start from db ?>', 'StartTimeFromServer'); }
</script>

Display time in hours and minutes (00:00) and round seconds to minutes

I want the time to always show 0's when less than 10 for example: if the task took 3 hours and 7 minutes and 33 seconds it would be displayed as 03:08
Right now I have the buttons disabled after they are clicked so that you cant restart the timer
Here is the JS code
let startTime;
const timer = typeof performance !== `undefined` && typeof performance.now === `function` ? performance : Date;
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const display = document.getElementById('display');
startButton.onclick = () => {
console.debug('START')
startTime = timer.now();
startButton.disabled = "disabled";
};
stopButton.onclick = () => {
console.debug('STOP')
var totalSeconds = Math.round((timer.now() - startTime) / 1000);
var totalMinutes = Math.floor(totalSeconds / 60);
var totalHours = Math.floor(totalSeconds / 60 / 60);
var displaySeconds = totalSeconds - totalMinutes * 60;
var displayMinutes = totalMinutes - totalHours * 60;
var strDisplayTime =
(totalHours > 0 ? (totalHours + '0:') : '') +
(displayMinutes > 0 || totalHours > 00 ?
((displayMinutes >= 10 ? '' : '0') + displayMinutes + ':') : '00:00:') +
((displaySeconds >= 10 ? '' : '0') + displaySeconds)
display.innerHTML = strDisplayTime;
stopButton.disabled = "disabled";
};
Here is the HTML
<h1>
<!-- This shows the heading of the entire checklist -->
Master on Call Checklist
</h1>
<ul class="checklist ng-pristine ng-untouched ng-valid ng-isolate-scope ui-sortable" ui-sortable="sortableOptions" ng-model="task">
<li>
<h2>
<!-- This shows the heading of task that need to be constantly looked at -->
<a href="#">
Tasks that need to be constantly checked throughout the week
</a>
</h2>
</li>
<button type="button" id="start">Start Task</button>
<p style="float:left;"></p>
<!-- Heading to review cameras and adjest as needed -->
<a>
Review cameras and adjest as needed
</a>
<button type="button" id="stop">Finished Task</button>
<div id="display"></div>
You need to add +((timer.now() - startTime) / 1000 > 30) to totalMinutes and you need to calculate it mod 60. JSFiddle.
let startTime;
const timer = typeof performance !== `undefined` && typeof performance.now === `function` ? performance : Date;
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const display = document.getElementById('display');
startButton.onclick = () => {
startTime = timer.now();
startButton.disabled = "disabled";
};
stopButton.onclick = () => {
var totalSeconds = Math.round((timer.now() - startTime) / 1000);
var totalMinutes = Math.floor(totalSeconds / 60 + +((timer.now() - startTime) / 1000 > 30));
var totalHours = Math.floor(totalSeconds / 60 / 60);
var displaySeconds = totalSeconds % 60;
var displayMinutes = totalMinutes % 60;
var strDisplayTime =
(totalHours > 0 ? (totalHours + '0:') : '') +
(displayMinutes > 0 || totalHours > 00 ?
((displayMinutes >= 10 ? '' : '0') + displayMinutes + ':') : '00:00:') +
((displaySeconds >= 10 ? '' : '0') + displaySeconds)
display.innerHTML = strDisplayTime;
stopButton.disabled = "disabled";
};
Try this one:
var fixedDisplaySeconds = ( '0' + displaySeconds ).substr( -2 );
var fixedDisplayMinutes = ( '0' + displayMinutes ).substr( -2 );
var fixedStrDisplayTime = fixedDisplaySeconds + ':' + fixedDisplayMinutes;
Basically, always add '0' at the beginning and then get the last 2 characters - if time was 1, then '0' + 1 = '01' - last 2 characters is '01'. Then if time is 11, '0' + 11 = '011' - get the last 2 characters and you get '11'.
You could create a Date directly from your millisecond counter and use the .getUTCHours() and getUTCMinutes() methods to format it as HH:MM.
// 3h07m33s in milliseconds
var ms = (3 * 3600 + 7 * 60 + 33) * 1000;
// create date (in the year 1970, which is OK)
var d = new Date(ms + 30000);
// format date as HH:MM
var strDisplayTime =
('0' + d.getUTCHours()).slice(-2) + ':' +
('0' + d.getUTCMinutes()).slice(-2);
console.log(strDisplayTime);
For browsers supporting it, you could also use .toLocaleString(). But it doesn't look like a very interesting option here.
// 3h07m33s in milliseconds
var ms = (3 * 3600 + 7 * 60 + 33) * 1000;
// create date (in the year 1970, which is OK)
var d = new Date(ms + 30000);
// format date as HH:MM
var strDisplayTime = d.toLocaleString(
'en-US',
{
timeZone: 'UTC', // we've created a UTC Date, so we must display it as such
hour12 : false, // use 24-hour format
hour : '2-digit', // display hours as two digits
minute : '2-digit' // display minutes as two digits
}
);
console.log(strDisplayTime);

How to calculate duration between two times in Google scripts for spreadsheet [duplicate]

This question already exists:
Google scripts subtracting times
Closed 7 years ago.
I would like to create a custom function that calculates the duration between two or more hours. The result can be positive or negative.
Other people can benefit using the function in any given coordinates not limiting to a specific range.
Example input:
Inputs: Output:
A B C D
-26:55 06:38 22:39 -04:16
02:19 00:00 04:33 02:19
I've tried without success many alternatives:
function saldo(A,B,C) { // best desired...
if(A == 0) {
return (-B)+C ;
}
else if (A<0 && (-A)<C && (-A)-C<B){
return (A)+C-B;
}
else if (A<0 && (-A)>C){
return (-B);
}
function xis(A,B) {
// var addedDate = sheet.getRange(1,1).getValue();
// var a1 = Utilities.formatDate(A, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "HH:mm");
// var b1 = Utilities.formatDate(B, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "HH:mm");
var a1 = new Date.getHours(A) + date.getMinutes(A);
var b1 = new Date.getHours(B) + date.getMinutes(B);
if (a1 > b1){
return B;
}
else {
return A;
}
}
function tentativa(a,b){
var t1 = a.getTime();
var t2 = b.getTime();
var outnumber = t1 - t2;
return Utilities.formatDate(new Date(outnumber), "GMT-3", "hh:mm");
}
function worked(time1,time2)
{
//var time1;
//var time2;
var outnumber = time1 - time2;
// return msToTime(outnumber)
return msToTime(outnumber);
// return Utilities.formatDate(new Date(outnumber), "GMT", "HH:mm");
}
function msToTime(duration) {
var milliseconds = parseInt((duration%1000)/100)
, seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24);
// hours = hours : hours;
// minutes = minutes : minutes;
// seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
You should only need 2 inputs to find the difference between two hour variables.
I have a small javascript code snippet which takes 2 inputs in hh:mm format and outputs the difference. You could extrapolate this logic for hh:mm:ss formats. You can call the function repeatedly to solve for 3 or more inputs.
// Code snippet to calculate the difference between 2 inputs of time in hh:mm 24hrs format
// Author: Harish Narayanan
// Date: 04-May-2015
function getHourDiff(a, b) {
if (!isValidHour(a) || !isValidHour(b)) {
return "Invalid input(s)";
}
var h1 = a.split(":"), h2 = b.split(":");
var h = 0, m = 0;
h = h1[0] - h2[0];
m = h1[1] - h2[1];
if (h < 0) {
h = -h;
m = -m;
}
if (h == 0) {
m = Math.abs(m);
}
if (m < 0) {
m = m + 60;
h = h - 1;
}
return h+":"+m;
}
function isValidHour(hour) {
hourPattern = "^([01]?[0-9]|2[0-3]):[0-5][0-9]$";
if (hour.match(hourPattern)) {return true;}
return false;
}

Recurrent Javascript countdown

I have an annoying problem, i have trying to implement a simple 10 or 15 minute recurrent countdown. i have tried jQuery but it just gives me options to count down to a date and stops after the countdown is finished.
I found the below code Here but i cant figure it to remove the days and make it to count down for 10 or 15 minuters. Can someone please help me?
<div id="countre3">Loading...</div>
<script type="text/javascript">
function mycountre(o, timeArray){
var countre = document.getElementById(o);
if(!countre) {
return;
}
// helper functions
function mksec(day, h, m, s){ return day*24*60*60+h*60*60+m*60+s; }
function toTimeString(sec, showZero){
var d=Math.floor(sec/(60*60*24))
var h=Math.floor(sec/(60*60)%24);
var m=Math.floor((sec/60) % 60);
var s=sec % 60;
var ret=d+'days '+h+'hrs '+m+'min '+s+'sec';
if(showZero){
return ret;
}else if(d==0 && h==0 && m==0){
return s+'sec';
}else if(d==0){
return h+'hrs '+m+'min '+s+'sec';
}else if(d==0 && h==0){
return m+'min '+s+'sec';
}else {
return ret;
}
}
//
var secArray = [];
var dayNow = new Date().getDay();
for(var i=0;i<timeArray.length;i++){
var day=timeArray[i][0];
if(day==-1){
day=dayNow;
}
secArray.push({
day: timeArray[i][0],
sec: mksec(day, timeArray[i][2], timeArray[i][2], timeArray[i][3]),
msg: timeArray[i][4] || false,
showZero: timeArray[i][5] || false
});
}
secArray.sort(function(a,b){ return a.sec-b.sec;});
// timer code - will be called around each second (~1000 ms)
function updatecountre(){
// get current UTC time in seconds
var d=new Date();
var secNow = mksec(d.getDay(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
// find next event
var nextIndex=0;
for(var i=0;i<secArray.length; i++){
var diff = secArray[i].sec-secNow;
if(diff>0){
nextIndex=i;
break;
}
}
//
var diff=secArray[nextIndex].sec-secNow;
var prevDiff=diff;
if(diff<0){
var dayDiff = 6-secArray[nextIndex].day;
if(secArray[nextIndex].day == -1){
dayDiff=0;
}
diff=(dayDiff+1)*24*60*60-Math.abs(diff);
}
var str='';
// get message if there is any set
if(secArray[nextIndex].msg){
str=secArray[nextIndex].msg;
}
var timeString = toTimeString(diff, secArray[nextIndex].showZero);
if(str.match('#{countre}')!=null){
str=str.replace(/#{countre}/, timeString);
}else if(str.indexOf(' ')==0){ // message starts with space
str=timeString+str;
}else{ // no specific hint where to put countre, so display it after message
str+=timeString;
}
countre.innerHTML=str;
}
setInterval(updatecountre, 1000);
};
mycountre('countre3', [ [5, 5, 0, 0, '<center><b>Next Turns are Due in </b><p class="smalltext"> #{countre}</center>', false] ]);
</script>
Try this:
function mycountre(countdownId, countdownSeconds, countdownLooping){
var countre = document.getElementById(countdownId); // get html element
if (!countre) {
return;
}
var target = new Date().getTime() + 1000 * countdownSeconds; // target time
var intervalId; // id of the interval
// update function
function updatecountre(){
var time = Math.floor((target - new Date().getTime()) / 1000); // countdown time in seconds
if (time < 0) { // if countdown ends
if (countdownLooping) { // if it should loop
target += 1000 * countdownSeconds; // set new target time
time = Math.floor((target - new Date().getTime()) / 1000); // recalculate current time
} else { // otherwise
clearInterval(intervalId); // clear interval
time = 0; // set time to 0 to avoid displaying negative values
}
}
// split time to seconds, minutes and hours
var seconds = '0' + (time % 60);
time = (time - seconds) / 60;
var minutes = '0' + (time % 60);
time = (time - minutes) / 60;
var hours = '0' + time;
// make string from splited values
var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
countre.innerHTML = str;
}
intervalId = setInterval(updatecountre, 200); // start interval to execute update function periodically
};
mycountre(
'countre3', // id of the html element
15 * 60, // time in seconds (15min here)
true // loop after countdown ends?
);
Working demo: http://jsfiddle.net/Xv3jx/1/
Small attempt for a jQuery plugin - more generic without minute/hour calc to avoid that the exaple gets too big:
(function($) {
$.fn.countdown = function(params) {
this.each(function() {
container = $.extend({
t: $(this),
stepSize: 1000, // milliseconds
duration: 3600, // seconds
offset: 0,
stepCallback: function() {},
finishCallback: function() {},
interval: function() {
if (this.offset>this.duration) {
this.finishCallback();
} else {
this.stepCallback();
}
this.offset += this.stepSize/1000;
}
}, params);
setInterval(function() {
container.interval();
}, container.stepSize);
});
return this;
};
})(jQuery);
Can be used with:
$('.main').countdown({
stepCallback: function() { console.log('step');},
finishCallback: function() { console.log('done');}
});
A simple countdown would then be implemented like this:
$('.main').countdown({
duration: 300,
stepCallback: function() {
var time = this.duration-this.offset
var seconds = '0' + (time % 60);
time = (time - seconds) / 60;
var minutes = '0' + (time % 60);
time = (time - minutes) / 60;
var hours = '0' + time;
var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
$(this.t).html(str);
},
finishCallback: function() { $(this.t).html('tadaaa'); }
});
Cheers

Categories

Resources