Skip to main content

jQuery setTimeout() Function Examples

By James Hibbard



Learning jQuery 3 Fifth Edition

🤓 All the power of JavaScript in a simpler format

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 Delayed Magnific Popup modal by SitePoint (@SitePoint) on CodePen.

If you don’t see the popup open, please visit CodePen and run the demo there.


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

var timeoutID = scope.setTimeout(function[, delay, param1, param2, ...]);
var timeoutID = scope.setTimeout(function[, delay]);
var timeoutID = scope.setTimeout(code[, delay]);


  • timeoutID is a numerical ID, which can be used in conjunction with clearTimeout() to cancel the timer.
  • scope refers to the Window interface or the WorkerGlobalScope interface.
  • function is the function to be executed after the timer expires.
  • 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.

Note: the square brackets [] denote optional parameters.

setTimeout vs window.setTimeout

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

Well, when running code in the browser, scope would refer to the global window object. Both setTimeout and window.setTimeout refer to the same function, the only difference being that in the second statement we are referencing the setTimeout method as a property of the 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 problems to worry about.

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.

Fill the gaps in your JS knowledge

Build your JavaScript skills on a rock-solid foundation.

Read the book now

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 IE9 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

Using Arrow Functions with setTimeout

Arrow functions were introduced with ES6. They have a much shorter syntax than a regular function:

(param1, param2, paramN) => expression

You can of course use them with setTimeout, but there’s one gotcha to be aware of — namely, that arrow functions don’t have their own this value. Instead, they use the this value of the enclosing lexical context.

Using a regular function:

const person = {
  firstName: "Jim",
  introduce: function() {
    console.log(`Hi, I'm ${this.firstName}`);

// Hi, I'm Jim

Using an arrow function:

const person = {
  firstName: "Jim",
  introduce: () => {
    console.log(`Hi, I'm ${this.firstName}`);

// Hi, I'm undefined

In the second example, this points to the global window object (which doesn’t have a firstName property).

This can trip us up when using arrow functions with setTimeout. Previously we saw how we can supply a function called in a setTimeout with the correct this value:

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

This won’t work when using an arrow function in the introduce method, as the arrow function doesn’t have its own this value. The method will still log undefined.

Cleaner Code with Arrow Functions and setTimeout

However, because arrow functions don’t have their own this value it can also work to our advantage.

Code like this …

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


… can be rewritten more concisely with an arrow function:

const person = {
  firstName: "Jim",
  delayedIntroduce() {
      () => { console.log(`Hi, I'm ${this.firstName}`); }, 1000


If you’d like a primer on arrow functions, please read ES6 Arrow Functions: Fat and Concise Syntax in JavaScript.

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, the kittens get it. However, if you press the Stop countdown button, 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 SetTimeout Kittens 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’ve 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’d like to learn more, there’s a whole library of JavaScript books in SitePoint Premium.

If you’d 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.

Currently I work for SitePoint as editor of their JavaScript hubs and technical editor for various books (e.g. JavaScript: Novice to Ninja and Jump Start Vue.js). I also work as a network admin and freelance web dev, where I spend a fair bit of my time working on Rails apps.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.