By James Hibbard

jQuery setTimeout() Function Examples

By James Hibbard


For more on working with animations in the front-end, watch our video tutorial on Reviewing CSS Animation Performance.

setTimeout is a native JavaScript function (although it can be used with a library such as jQuery, as we’ll see later on), which calls a function or executes a code snippet after a specified delay (in milliseconds). This might be useful if, for example, you wished to display a popup after a visitor has been browsing your page for a certain amount of time, or you want a short delay before removing a hover effect from an element (in case the user accidentally moused out).

Basic setTimeout Example

To demonstrate the concept, the following demo displays a popup, two seconds after the button is clicked.

See the Pen Set Timout modal by SitePoint (@SitePoint) on CodePen.


From the MDN documentation, the syntax for setTimeout is as follows:

var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);


  • timeoutID is a numerical id, which can be used in conjunction with clearTimeout() to cancel the timer.
  • func is the function to be executed.
  • code (in the alternate syntax) is a string of code to be executed.
  • delay is the number of milliseconds by which the function call should be delayed. If omitted, this defaults to 0.

setTimeout vs window.setTimeout

You’ll notice that the syntax above uses window.setTimeout. Why is this?

Well, setTimeout and window.setTimeout are essentially the same, the only difference being that in the second statement we are referencing the setTimeout method as a property of the global window object.

In my opinion this adds complexity, for little or no benefit—if you’ve defined an alternative setTimeout method which would be found and returned in priority in the scope chain, then you’ve probably got bigger issues.

For the purposes of this tutorial, I’ll omit window, but ultimately which syntax you chose is up to you.

Examples of Use

setTimeout accepts a reference to a function as the first argument.

This can be the name of a function:

function explode(){
setTimeout(explode, 2000);

A variable that refers to a function:

var explode = function(){
setTimeout(explode, 2000);

Or an anonymous function:

}, 2000);

It is also possible to pass setTimeout a string of code for it to execute:

setTimeout("alert('Boom!');", 2000);

This is however not advisable for the following reasons:

  • It’s hard to read (and thus hard to maintain and/or debug)
  • It uses an implied eval() which is a potential security risk
  • It’s slower than the alternatives, as it has to invoke the JS interpreter.

This StackOverflow question offers more information on the above points.

Passing Parameters to setTimout

In a basic scenario, the preferred, cross-browser way to pass parameters to a callback executed by setTimeout is by using an anonymous function as the first argument.

In the following example, we select a random greeting from a greetings array and pass this random greeting as an parameter to a greet function, which is executed by setTimeout with a delay of one second.

function greet(greeting){

function getRandom(arr){
  return arr[Math.floor(Math.random()*arr.length)];

var greetings = ["Hello", "Bonjour", "Guten Tag"],
    randomGreeting = getRandom(greetings);

}, 1000);

JS Bin

An Alternative Method

As can be seen from the syntax at the top of the article, there is a second method of passing parameters to a callback executed by setTimeout. This involves listing any parameters after the delay.

With reference to our previous example, this would give us:

setTimeout(greet, 1000, randomGreeting);

Unfortunately, this doesn’t work in IE 9 or below where the parameters come through as undefined. There is however, a pollyfill available on MDN.


The Problem With “this”

Code executed by setTimeout is run in a separate execution context to the function from which it was called. This is problematic when the context of the this keyword is important.

var person = {
  firstName: "Jim",
  introduce: function(){
    console.log("Hi, I'm " + this.firstName);

// Outputs: Hi, I'm Jim

setTimeout(person.introduce, 50);
// Outputs: Hi, I'm undefined

The reason for this output is that in the first example, this points to the person object, whilst in the second example this points to the global window object (which doesn’t have a firstName property).

To counteract this, there are various measures:

Explicitly set the value of this

You can do this using bind(), a method which creates a new function that, when called, has its this keyword set to the provided value (in our case the person object). This would give us:

setTimeout(person.introduce.bind(person), 50);

Note: bind was introduced in ECMAScript 5, so will only work in more modern browsers. You can read more about it (and other methods of setting the value of this) in this SitePoint article.

Use a Library

Many libraries come with built in functions to address this issue. For example, jQuery’s jQuery.proxy() method. This takes a function and returns a new one that will always have a particular context. In our case, that would be:

setTimeout($.proxy(person.introduce, person), 50);

JS Bin

Cancelling a Timer

The return value of setTimeout is a numerical id which can be used to cancel the timer in conjunction with the clearTimeout() function.

var timer = setTimeout(myFunction, 3000);

Let’s see this in action. In the following Pen, if you click on the “Start countdown” button, a countdown will begin. If the countdown completes, then the kittens get it. However, if you press the “Stop countdown” button, then the timer will be halted and reset (if you don’t see a cool effect when the countdown reaches zero, re-run the pen using the button in the bottom-right of the embed).

See the Pen CSS3 animation effects for Magnific Popup by SitePoint (@SitePoint) on CodePen.

Wrapping Up

One potential caveat to be aware of is the fact that setTimeout is asynchronous, in that it queues the function reference it receives to run once the current call stack has finished executing. It doesn’t however, execute concurrently, or on a separate thread (due to JavaScript’s single-threaded nature).

  }, 0);

// Outputs: 1, 3, 2

There is also some confusion between the use of the native JavaScript setTimeout function and jQuery’s delay method.

The delay method is meant specifically for adding a delay between methods in a given jQuery queue. There is no possibility to cancel the delay. For example, if you wanted to fade an image into view for one second, have it visible for five seconds, and then fade it out for a period of one second, you could do the following:


setTimeout is best used for everything else.

Finally, if you need to repeatedly execute code after a specified delay, then setInterval is more suited to the job. You can read more about this function here.


In this article, I have demonstrated how to use setTimeout to delay the execution of a function. I have also shown how to pass parameters to setTimeout, maintain the this value inside its callback and also how to cancel a timer.

If you would like to discuss the content of this article, please do so in the comments. If however, you have run into a coding problem regarding the use of setTimeout (or anything else, really), then please head to the SitePoint forums. You can log in with (Google, Facebook, Twitter, Yahoo, GitHub, or by creating an account). Then head to the JavaScript forum and start a thread stating your problem.

Why stop your learning there? Watch Reviewing CSS Animation Performance for more on timing examples.

  • Isaac orija

    THanks for this great article.

Get the latest in JavaScript, once a week, for free.