[JavaScript, jQuery] Timer

Timers can be very useful or annoying for some users. So they need to be used sparingly. JavaScript provides native functions for timers or you can use jQuery’s delay()  for easier use.  

1. JavaScript Timer Functions

In JavaScript, the “window” object provides the following methods for timers:

  • setInterval(code,millisec) : calls the function at specified intervals (in milliseconds)
  • setTimeout(code,millisec) : calls the function after a specified number of milliseconds
  • clearInterval(id) : clears a timer set with setInterval()
  • clearTimeout(id) : clears a timer set with setTimeout()

The methods of the “window” object do not need to specify the object. Therefore you can call these methods just like global functions at any place.


2. One-shot Timer

The “setTimeout()” is used to create a one-shot timer. It triggers the code only once. The simplest code can be the following. You can specify the function name instead of the code block.

$(document).ready(function () {
  setTimeout("alert('Hello, World')", 5000); // 5 secs

The “clearTimeout()” can clear the timer before the timer is triggered.


3. Interval Timer

An interval timer triggers the code repeatedly until the timer is cleared.

  <input id="start" type="button" value="Start" />
  <input id="stop" type="button" value="Stop" />
  <div id="status">Timer Stopped</div>


$(document).ready(function () {
  var intervalTimer;
  $('#start').click(function () {
    intervalTimer = setInterval("alert('Hello, World')", 3000); // 3 secs
    $('#status').html('Timer Started');
  $('#stop').click(function () {
    $('#status').html('Timer Stopped');


4. Refresh a Page

With a timer, you can refresh a page periodically. To reload a page, you need to use “reload()” method of the “location” object. You can access the “location” object through the “window” object.

$(document).ready(function () {
  var d = new Date();
  setInterval("location.reload()", 3 *60*1000); // 3 mins


5. JQuery’s “delay()” Function

jQuery does not provide the timer functions. The “delay()” function works with other animation functions and makes an effect of a timer. The following code shows content for 10 seconds and hide it again.

<input id="delay" type="button" value="Show it and Hide it" />
<div id="greet">Hello, World!</div>


$(document).ready(function () {
  $('#delay').click(function () {
    $('#greet').fadeIn('slow').delay(2 * 1000).fadeOut('slow');

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s