JASON CHAVANNES  

jQuery Timer

Project Home   •   View Demo   •   Download   •   Other Web Development Tutorials


$.timer( [ action ] , [ time ] , [ autostart ] )

action A Function to be called by the timer.

time A Number determining how long between actions in milliseconds.

autostart A Boolean indicating whether to start the timer. Defaults to false.

Usage

timer.set(options)
timer.play(reset)  // Boolean. Defaults to false.
timer.pause()
timer.toggle(reset)  // Boolean. Defaults to false.
timer.stop()  // Pause and resets
timer.reset()
timer.once(time)  // Number. Defaults to 0.
timer.isActive  // Returns true if timer is running

Example

var timer = $.timer(function() {
	alert('This message was sent by a timer.');
});

timer.set({ time : 5000, autostart : true });

Comments

Mike BApril 7, 2014 at 12:53 pm

Hi Jason,
A handy bit of code. One issue I had is that it does not appear that setTimer() can be used to change the interval. I create an instance of the timer and based on a selection the interval can be changed dynamically. I call stop(), then setTimer() with the new interval, then play().
I modified setTimer()

if (isNaN(time)) {
time = this.intervalTime;
} else {
this.intervalTime = time;
}


That appears to work, allowing me to reset the interval.
Can you tell me if there is a more appropriate way to do this through the widget?

larishaDecember 23, 2013 at 8:32 pm

Can you please tell me the code for timer which will not reset when we click on next or previous button....please tell it fast

robertDecember 22, 2013 at 7:37 am

Is it possible to start "Example1-Stopwatch" only after pressing Play/Pause button?
What code should I add?

arulrajNovember 29, 2013 at 5:05 am

can you send the php timer coding

JasonOctober 29, 2013 at 9:21 pm

FYI: Browsers usually pause Javascript for inactive tabs. That is why the timer stops. There isn't an easy way around this, you either have to keep track of absolute time and manually advance the timer when the tab becomes active again or use web workers, etc. http://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome

gimpadelicOctober 25, 2013 at 9:04 am

Answered my own question by looking at the code. There is an undocumented method called go() - works great! Thanks for a great plugin, btw!

gimpadelicOctober 25, 2013 at 8:56 am

Is there a way to force the timer function to fire? In other words, I have an external event that happens, and when I catch it, I want to basically "speed up" the timer to the end of its current cycle, so the event fires, and then have the timer continue on counting normally towards the next cycle. Hope that makes sense, and thanks in advance for any ideas!

Suresh kumarOctober 23, 2013 at 12:09 am

Here is my code which is I tried to use it.
Thanks









/**
* jQuery Timer doesn't natively act like a stopwatch, it only
* aids in building one. You need to keep track of the current
* time in a variable and increment it manually. Then on each
* incrementation, update the page.
*
* The increment time for jQuery Timer is in milliseconds. So an
* input time of 1000 would equal 1 time per second. In this
* example we use an increment time of 70 which is roughly 14
* times per second. You can adjust your timer if you wish.
*
* The update function converts the current time to minutes,
* seconds and hundredths of a second. It then outputs that to
* the stopwatch element, $stopwatch, and then increments. Since
* the current time is stored in hundredths of a second so the
* increment time must be divided by ten.
*/
var Example1 = new (function() {
var $stopwatch, // Stopwatch element on the page
incrementTime = 70, // Timer speed in milliseconds
currentTime = 0, // Current time in hundredths of a second
updateTimer = function() {

$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
},
init = function() {

$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
$(init);
});

var count = 0,
timer = $.timer(function() {

count++;
$('#counter').html(count);
});
timer.set({ time : '', autostart : true });


// Common functions
function pad(number, length) {

var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
function formatTime(time) {

var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "") + ":" + pad(sec, 2) + ":" + hundredths;
}



Project home: http://jchavannes.com/jquery-timer
45:00:00





Suresh kumarOctober 23, 2013 at 12:07 am

I have used this timer up script in my localhost project and I have defined fixed minutes in count up like 45:00:00 then after over 60 seconds again minutes start form 01 but it shuld be start from 46:01:00.
please anyone Have any idea why it is happening. please post the answers.

niceSeptember 30, 2013 at 1:07 am

hello

JustdmitrySeptember 13, 2013 at 11:29 pm

renoidooizawa

the timer is freeze when browser is lost focus (e.g when it change into another tabs, or when it minimized), could you help me why this happen, because it doesn't matter when we use setInterval method, thanks :D


var globalWarnings = [];
var leavePageFlag = true;
var $countdown;
var $form;
var incrementTime = 70;
var startTime = 20000; //300000 = 5 minutes (in milliseconds)
var currentTime = startTime;
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
function formatTime(time) {
time = time / 10;
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60);
// hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) /*+ ":" + hundredths*/;
}

if (window.localStorage) {
var currentTimeStamp = new Date();

try {
localStorage.setItem('sessionStartTime', currentTimeStamp.getTime());
} catch(err) {
if (err.code == QUOTA_EXCEEDED_ERR) {
myAlert('Not enough free space in localStorage!', 'error');
}
}

var sessionTimer = new (function() {

$(function() {
// Setup the timer
$countdown = $('#countdown');
sessionTimer.Timer = $.timer(updateTimer, incrementTime, true);

$('#refreshSession').click(function(){
// @todo AJAX funkcja dla odnawiania sessji
currentTime = startTime;
currentTimeStamp = new Date();
localStorage.setItem('sessionStartTime', currentTimeStamp.getTime());
$('#sessionTimer').removeClass('expired');
sessionTimer.Timer.play();
});
});

function updateTimer() {
// Output timer position
var timeString = formatTime(currentTime);
$countdown.html(timeString);

// If timer is complete, trigger alert
if (currentTime == 0) {
sessionTimer.Timer.stop();
$('#sessionTimer').addClass('expired');
sessionTimer.resetCountdown();
return;
}

// Increment timer position
currentTime -= incrementTime;
if (currentTime < 0) currentTime = 0;

}

this.resetCountdown = function() {
sessionTimer.Timer.stop().once();
};

});
} else {
globalWarnings.push('Warning! - HTML5 Local Storage');
}

$(window).blur(function() {
if (leavePageFlag) {
leavePageFlag = false;

}
});
$(window).focus(function() {
if (!leavePageFlag && currentTime > 0) {
var lastSessionTime = parseInt(localStorage.getItem('sessionStartTime'), 10);
currentTimeStamp = new Date();
currentTime = currentTimeStamp.getTime() - lastSessionTime;
if (currentTime < startTime) {
currentTime = startTime - currentTime;
sessionTimer.Timer.play();
} else {
$('#sessionTimer').addClass('expired');
currentTime = 0;
sessionTimer.resetCountdown();
}
leavePageFlag = true;
}
});

JustdmitrySeptember 13, 2013 at 11:28 pm

renoidooizawa

the timer is freeze when browser is lost focus (e.g when it change into another tabs, or when it minimized), could you help me why this happen, because it doesn't matter when we use setInterval method, thanks :D


var globalWarnings = [];
var leavePageFlag = true;
var $countdown;
var $form;
var incrementTime = 70;
var startTime = 20000; //300000 = 5 minutes (in milliseconds)
var currentTime = startTime;
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
function formatTime(time) {
time = time / 10;
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60);
// hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) /*+ ":" + hundredths*/;
}

if (window.localStorage) {
var currentTimeStamp = new Date();

try {
localStorage.setItem('sessionStartTime', currentTimeStamp.getTime());
} catch(err) {
if (err.code == QUOTA_EXCEEDED_ERR) {
myAlert('Not enough free space in localStorage!', 'error');
}
}

var sessionTimer = new (function() {

$(function() {
// Setup the timer
$countdown = $('#countdown');
sessionTimer.Timer = $.timer(updateTimer, incrementTime, true);

$('#refreshSession').click(function(){
// @todo AJAX funkcja dla odnawiania sessji
currentTime = startTime;
currentTimeStamp = new Date();
localStorage.setItem('sessionStartTime', currentTimeStamp.getTime());
$('#sessionTimer').removeClass('expired');
sessionTimer.Timer.play();
});
});

function updateTimer() {
// Output timer position
var timeString = formatTime(currentTime);
$countdown.html(timeString);

// If timer is complete, trigger alert
if (currentTime == 0) {
sessionTimer.Timer.stop();
$('#sessionTimer').addClass('expired');
sessionTimer.resetCountdown();
return;
}

// Increment timer position
currentTime -= incrementTime;
if (currentTime < 0) currentTime = 0;

}

this.resetCountdown = function() {
sessionTimer.Timer.stop().once();
};

});
} else {
globalWarnings.push('Warning! - HTML5 Local Storage');
}

$(window).blur(function() {
if (leavePageFlag) {
leavePageFlag = false;

}
});
$(window).focus(function() {
if (!leavePageFlag && currentTime > 0) {
var lastSessionTime = parseInt(localStorage.getItem('sessionStartTime'), 10);
currentTimeStamp = new Date();
currentTime = currentTimeStamp.getTime() - lastSessionTime;
if (currentTime < startTime) {
currentTime = startTime - currentTime;
sessionTimer.Timer.play();
} else {
$('#sessionTimer').addClass('expired');
currentTime = 0;
sessionTimer.resetCountdown();
}
leavePageFlag = true;
}
});

David BAugust 24, 2013 at 3:24 pm

Can it keep going to show elapse hours?

Abhishek SaxenaAugust 1, 2013 at 1:03 pm

Has anybody got the solution of problem that timer stops as soon as browser goes out of focus.

DoganJune 18, 2013 at 1:38 am

any solution for browser minimaze issue?

Poonam kumari giriJune 15, 2013 at 10:47 pm

i want the timer code

JohnJune 13, 2013 at 2:25 pm

Good job! Very easy to set up and I find it super useful in my project.

Thanks!

ScottMay 10, 2013 at 1:21 pm

Example 4 is messed up by the way . . .

AlphaApril 23, 2013 at 6:35 am

Please versioning the library!!!!

ChrisMarch 28, 2013 at 12:04 pm

Nice! Thanks

MonikaMarch 21, 2013 at 6:52 am

gR8 work :D

ShankarMarch 15, 2013 at 5:29 am

I am using timer.once(), but not working pause method please help...

Sam JohnstoneMarch 11, 2013 at 7:30 am

Is there a way to change the interval of the counters output for example 4?
What I mean is change it from counting 1,2,3,4,5 to 10,20,30,40,50.
Thanks

Phong ThaiFebruary 18, 2013 at 7:07 am

simple but nice script, thank for sharing

NelsonFebruary 18, 2013 at 3:12 am

If i change the website tab or minimize the page the counter pauses... can we change that?

AldevJanuary 29, 2013 at 2:09 am

Nice work.
Thanks a lot !

Ruben BocanegraJanuary 10, 2013 at 9:26 am

Thanks for the script !!!

freeTownJanuary 8, 2013 at 8:15 am

having the same problem as renoidooizawa when I leave the page the timer seems to pause. Any Ideas on how to fix ? Thanks

renoidooizawaJanuary 7, 2013 at 8:34 pm

the timer is freeze when browser is lost focus (e.g when it change into another tabs, or when it minimized), could you help me why this happen, because it doesn't matter when we use setInterval method, thanks :D

renoidooizawaJanuary 7, 2013 at 8:33 pm

the timer is freeze when browser is lost focus (e.g when it change into another tabs, or when it minimized), could you help me why this happen, because it doesn't matter when we use setInterval method, thanks :D

FrankDecember 29, 2012 at 5:47 pm

Hi Jason,

Great plugin! I've got a question.. how to attach a callback function for the toggle function? or the "pause" one; Let me explain, I wish I could get the time currently pause time, I want to get the exact time the user pauses the timer. How to achieve that?

Thanks in advanced.
Frank

kckomahanDecember 5, 2012 at 4:51 am

How to handle timer during postback? is there any inbuilt feature?

SHANINovember 19, 2012 at 8:58 am

jayjitOctober 1, 2012 at 5:02 am

When we go through any alert() timer stop at that time. Count you please tell the solution to run timer at that time as well

ChrisSeptember 18, 2012 at 2:22 pm

I'm having an issue where it doesn't appear that timer.remaining ever decrements. The timer seems to count down as needed, but if I check the remaining time in an onclick event, it still shows the original timer value. Anybody have theories?

rajaSeptember 13, 2012 at 3:06 am

hai sir i wont a timer .
inthat timer show my page and working reverse. i dont know how to implement it please help me...

thank you

JMSeptember 2, 2012 at 8:17 pm

can i download the source?

Tod B.August 1, 2012 at 10:52 pm

Really weird issue...in chrome the timer is slower and doing real-time...all other browsers realtime except chrome, odd..

JasonMay 24, 2012 at 12:13 am

I posted an update, the new version uses .isActive which addesses an issue some users were having.

jamesMay 18, 2012 at 11:32 am

Found same problem (DenisNovember 22, 2011 at 2:47 am) mentioned. Found that timer.active gets turned into a number and incremented periodically during the course of JQuery ajax calls.

jurajMarch 26, 2012 at 11:43 am

you can change the once function to this and then the stop works

this.once = function(time) {
var timer = this;
this.active = true;
if(isNaN(time)) {time = 0;}
this.timeoutObject=window.setTimeout(function() {timer.action();}, time);
return this;
};

MarkFebruary 24, 2012 at 5:14 pm

It appears you cannot stop() a timer started with once(). If you call once() and then stop() before the timeout, the timer fires anyway. this.timeoutObject does not get assigned on once().

AykutFebruary 15, 2012 at 5:39 am

I had the same bug as Denis mentioned November 22, 2011 at 2:47 am.

this.active is overlapping some other function or method. I changed this.active to this.isTimerActive and it solved my problem.

Maybe you can consider to change active code to isTimerActive.

Btw thank you Denis. That really saved my life.

alexonJanuary 25, 2012 at 7:05 am

Hello how can i stop the timer? please advise. thank you :)

JasonDecember 13, 2011 at 6:28 pm

stop() does both pause() and reset() and is probably the function you are looking for. reset() sets the time remaining back to full duration but does not effect whether the timer is active or not and pause() makes the timer inactive.

vossDecember 9, 2011 at 9:54 am

.reset()
What is reset supposed to do?
What is the best approach to stop and set back to ZERO?

thanks.

RoyDecember 4, 2011 at 2:18 am

A nice piece of work =)

DenisNovember 22, 2011 at 2:47 am

Found very weird "bug". Tried to attach this plugin to my webapp and it didn't work.

Problem was solved by replacing this.active -> this.isTimerActive in JS file.

Seems to me, that somewhere there was namespaces overlap, which caused a problem.

Ding-Wen ChenOctober 21, 2011 at 3:25 pm

Great plug-in!

I used it to auto rotation. However, I am using jQuery animate delay() function which gets paused by the timer plug-in. Is there anything I missed to have them separated?

JasonSeptember 24, 2011 at 8:04 pm

That is how it is supposed to behave; reset() clears the timer and then starts it again at full duration. If you want it to stop then do once() and then stop().

ZakSeptember 17, 2011 at 9:09 pm

Why is the default behavior to loop over and over again? When once() is called, then reset() is called, the timer starts looping over and over. Annoying.

ZakSeptember 17, 2011 at 3:16 am

Could you add a "loop quantity" option to this? In other words, give us more loop quantity options than just "once"

JasonJuly 30, 2011 at 11:29 pm

Yes, it is compliant with all major browsers

AlcatrazJuly 28, 2011 at 12:24 pm

is it cross-browser compliant?


Accepted HTML Tags: <a><pre><b><i><br>