Super Javascript
Home About RSS Guest Blogging 🐍 Snake

JavaScript setTimeout

JavaScript setTimeout

JavaScript’s setTimeout method will wait for an amount of time, and then perform a task that you specify. It takes two parameters, the function to call back that will perform the task, and a number of milliseconds to wait before the callback.

The callback might not happen exactly at the time specified depending on how busy the program is. It usually happens pretty close to the time specified, but don’t build a clock based on setTimeout. However do use setTimeout for any situation where a tiny bit of inaccuracy is OK, such as:

Here is how you use setTimeout: the first argument is the function that you want to be called back. The second is the time in milliseconds (thousandths of a second). This example below will pop up a message after 5 seconds has elapsed.

var reference = setTimeout(function(){
  alert('5 seconds has passed');
}, 5000);

The value returned to reference is a number indicating which call to setTimeout was used. This can be used later to cancel the setTimeout before it triggers. When I tested it the number was 2781, but it could be anything, and you only need it if you want to cancel the action later.

Why does setTimeout use a callback?

JavaScript programs run single-threaded, meaning that at any time, there is only one path through the program that is being run. If we had a method that made the program go ‘to sleep’ for say 5 seconds, then nothing else can happen in that program during those 5 seconds, because the one and only path through the program is paused. This could make the whole web page or app be unresponsive to the user for that time.

This is why setTimeout uses a callback. This allows the method to immediately pass back control to the program to carry on with other work. When the requested time has elapsed, the callback is called and run. It will have to wait for any code that is running to finish and then run your callback code.

JavaScript programs might be single-threaded, but that doesn’t mean that only one thing can happen at the same time. This is because JavaScript supports ‘asynchronous’ methods, which are methods that go and do something and then have a callback when they are done, in the same manner as setTimeout.

For example, there are methods to send data to a server or store data in the browsers ‘local storage’ that use callbacks to do this without blocking your JavaScript program. NodeJS, which allows you to run JavaScript programs directly on your computer or server, has callback methods to read and write files to disk. NodeJS is also single threaded.

Cancelling an action

You can cancel an action before it has elapsed. It is not common that you would want to do this with setTimeout, but it is more common with its sister function setInterval which calls a function and never stops unless you cancel it.

Anyway if you do need to cancel a setTimeout just call clearTimeout with the number returned from the setTimeout function. I have used scoping so that both functions can share the same reference.

var reference;

function createTimeout() {
  reference = setTimeout(function(){
    alert('5 seconds has passed');
  }, 5000);
}

// This could be called when a button is pressed.
function clearTimeout() {	
  clearTimeout(reference);
}

Summary

This tutorial covers setTimeout which is used to run some code at a later point in time. This request to run code later can be cancelled.

While you are here…

You like retro? Grab my free guide where I will take you step by step to make a classic arcade game in JS.

There are 8 chapters and I will send you a chapter per week by email:

  • Introduction to Snake
  • The Canvas: Your Portal To Pixel Perfect Drawing
  • Setting up a game loop
  • Keeping track of your snake
  • Responding to player’s key presses
  • Enforcing the rules of the game
  • Snake Food
  • Finishing up

To get the game subscribe below:

Want to have a quick play? Click on the game below, press X to start and use the arrow keys to move...