JavaScript timers

JavaScript Timers: setTimeout and setInterval Explained

JavaScript timers let us schedule code to run after a certain amount of time. They’re useful for delays, repeated tasks, and adding a bit of life to our code—like waiting before showing a message or running something every few seconds.

In this article, we’ll focus on how to use two built-in JavaScript functions: setTimeout and setInterval. You’ll see how they work, what their syntax looks like, and how to use them in fun, practical ways.

Understanding setTimeout

What is setTimeout

setTimeout is a JavaScript function that lets you run some code once, after a set amount of time (in milliseconds). It’s like telling your code, “Wait for a bit, then do this.”

For example, if you want to show a message 2 seconds after a page loads, setTimeout can do that. It’s perfect for things that should happen later, but only once.

Basic Syntax

The basic syntax of setTimeout looks like this:

setTimeout(function, delayInMilliseconds);

Here, function is the code you want to run later, and delayInMilliseconds is how long to wait before running the code (1 second = 1000 milliseconds).

For example, this code waits 3 seconds before saying “Hello”:

setTimeout(function() {
  console.log("Hello after 3 seconds!");
}, 3000);

It only runs once, after the delay.

Code Example: Making Tea After a Delay

Let’s say you’re making tea. First, you wait for the water to boil. That’s a perfect job for setTimeout — wait a few seconds, then show a message.

function boilWater() {
  console.log("Water is boiling...");
}

setTimeout(boilWater, 3000); // Waits 3 seconds

console.log("Waiting to boil...");

In this example, "Waiting to boil..." appears right away, because JavaScript doesn’t stop — it keeps going. Then after 3 seconds, boilWater runs and prints "Water is boiling...". This shows how setTimeout lets us delay actions without freezing the whole program.

Using Arrow Functions with setTimeout

Arrow functions make your code shorter and cleaner, especially when the function is simple. With setTimeout, they work just like regular functions, but take up less space.

Here’s an example:

setTimeout(() => {
  console.log("Tea is ready!");
}, 2000);

This waits 2 seconds, then prints "Tea is ready!". The arrow function () => { ... } replaces the longer function() { ... }, making it easier to read when you’re just doing one quick task.

Passing Arguments to the Function

Sometimes, you want to send information into the function that runs after the delay. setTimeout allows this by adding extra arguments after the delay time.

For example, if you want to greet someone by name, you can write a function that accepts a parameter, then pass the value when calling setTimeout:

function greet(name) {
  console.log("Hello, " + name + "!");
}

setTimeout(greet, 1000, "Edward");

Here, greet will run after 1 second, using "Edward" as the name inside the function.

You can also pass more than one argument if your function needs multiple values. For instance:

function welcome(name, drink) {
  console.log(name + ", your " + drink + " is ready!");
}

setTimeout(welcome, 2000, "Lucia", "green tea");

In this case, after 2 seconds, the welcome function runs with both "Lucia" and "green tea" as inputs. This shows how setTimeout can pass multiple pieces of information to the delayed function, making your code more flexible.

Cancelling setTimeout with clearTimeout

Sometimes, you may want to stop a delayed action before it happens. JavaScript lets you do this using clearTimeout.

When you call setTimeout, it gives back a timer ID. You can use this ID to cancel the timer before the delay finishes.

Here’s an example:

const timerId = setTimeout(() => {
  console.log("You'll never see this message!");
}, 5000);

clearTimeout(timerId);

console.log("Timeout cancelled.");

In this code, the message inside setTimeout is scheduled to run after 5 seconds. But before that, clearTimeout(timerId) stops it, so the message never appears. Instead, you immediately see "Timeout cancelled."

This way, you keep control over delayed actions and can stop them if needed.

Understanding setInterval

What is setInterval

setInterval is a JavaScript function that runs code repeatedly, over and over, every set amount of time (in milliseconds). Instead of running just once like setTimeout, it keeps running the code again and again until you tell it to stop.

This is useful when you want something to happen regularly—like a clock ticking or a message appearing every few seconds.

Basic Syntax

The basic way to use setInterval looks like this:

setInterval(function, delayInMilliseconds);

Here, function is the code you want to run repeatedly, and delayInMilliseconds is how often it runs, measured in milliseconds (1000 milliseconds = 1 second).

For example, this code runs a function every 2 seconds:

setInterval(() => {
  console.log("Hello every 2 seconds!");
}, 2000);

This keeps printing the message again and again, every 2 seconds, until you stop it.

Code Example: Cuckoo Clock

Imagine a cuckoo clock that sounds every 10 seconds. We can use setInterval to make this happen in code.

function cuckoo() {
  console.log("Cuckoo! 🕰️");
}

setInterval(cuckoo, 10000); // Every 10 seconds

Here, the cuckoo function runs every 10 seconds, printing the sound "Cuckoo! 🕰️". This shows how setInterval can create repeated actions that happen at regular time intervals—just like a clock ticking.

Here’s another example that shows the current time every second:

setInterval(() => {

  const now = new Date();
  console.log(now.toLocaleTimeString());

}, 1000);

This code runs every second and prints the current time in a readable format. It’s like having a digital clock right in your console.

Using Arrow Functions with setInterval

Arrow functions work great with setInterval when you want to keep your code short and simple. They behave just like regular functions but take less space.

Here’s an example:

setInterval(() => {
  console.log("Still ticking...");
}, 3000);

This runs the arrow function every 3 seconds, printing "Still ticking..." each time. It’s a clean way to write repeated actions with minimal code.

Passing Arguments to the Function

Just like with setTimeout, you can pass arguments to the function inside setInterval. After the delay time, these arguments are sent into the function each time it runs.

For example, if you want to repeat a message with a name, you can write:

function cheer(name) {
  console.log(name + ", keep going!");
}

setInterval(cheer, 2000, "Harry");

Here, the cheer function runs every 2 seconds, receiving "Harry" as an argument each time.

You can also pass multiple arguments if needed:

function announce(name, activity) {
  console.log(name + " is " + activity + "!");
}

setInterval(announce, 3000, "Fred", "shooting hoops");

This calls announce every 3 seconds with both "Fred" and "shooting hoops" as inputs. Passing arguments makes repeated functions flexible and easy to customize.

Stopping setInterval with clearInterval

Sometimes, you want to stop the repeated action after a certain time. You can do this using clearInterval, which cancels the timer created by setInterval.

Here’s an example that stops after 5 repeats:

let count = 0;

const intervalId = setInterval(() => {

  console.log("Bark!");

  count++;

  if (count === 5) {

    clearInterval(intervalId);
    console.log("No more barking.");

  }

}, 2000);

In this code, the message "Bark!" prints every 2 seconds. After it has run 5 times, clearInterval stops the repeating, and then it prints "No more barking."

This shows how you can control when to end a repeating task with clearInterval.

Combining setTimeout and setInterval

Chaining Timers

You can combine setTimeout and setInterval to create interesting timer chains—where one timer starts another. This lets you control timing more flexibly.

For example, here’s setTimeout used inside setInterval:

setInterval(() => {

  console.log("Get ready...");

  setTimeout(() => {
    console.log("Go!");
  }, 1000);

}, 3000);

In this code, every 3 seconds it prints "Get ready...". Then, after 1 more second, it prints "Go!". The setTimeout inside the setInterval creates a small delay between the two messages each cycle.

You can also do the opposite—use setInterval inside setTimeout—to start repeated actions after a delay. This chaining helps build timed sequences step-by-step.

Example: Countdown Timer

Here’s a simple countdown timer that counts down from 5 to 1, then prints "Go!".

let seconds = 5;

const countdown = setInterval(() => {

  console.log(seconds);
  seconds--;

  if (seconds === 0) {
    clearInterval(countdown);
    console.log("Go!");
  }

}, 1000);

This code runs every second, showing the current number. When the countdown reaches zero, it stops the timer with clearInterval and prints the final message. It’s a great way to see how timers can work together to create useful effects.

Of course! Here’s a well-written Conclusion section followed by the References section, formatted to match the tone and style of your article:

Conclusion

Timers in JavaScript give us the power to schedule code—either once with setTimeout, or over and over with setInterval. They’re simple tools, but incredibly useful.

Now you’ve seen how to use both of them: from waiting to boil tea, to repeating clock sounds, and even making countdowns. Whether it’s a short pause or regular updates, you now know how to control time in your programs.

References

Scroll to Top