Skip to content
  • Homepage
  • HTML
  • CSS
  • Symfony
  • PHP
  • How to
  • Contact
  • Donate

Teach Developer

Articles, Guides & Tips

How to use setTimeout and setInterval methods in JavaScript

Home  »  JavaScript   »   How to use setTimeout and setInterval methods in JavaScript
Posted on July 24, 2022July 24, 2022 No Comments on How to use setTimeout and setInterval methods in JavaScript
426

There are times when you don’t want to execute a function immediately. You want it to delay its execution or run repeatedly after a certain time interval. JavaScript provides us with two methods to achieve that: setTimeout and setInterval. In this article, we will discuss these two methods and how we can use them to schedule function calls in JavaScript.

setTimeout

The setTimeout the method runs a given function after a certain period. It sets a timer and executes the given function(callback) once the time expires. The syntax to use the setTimeout method is this:

const timerID = setTimeout(function, delay, arg1, arg2, ...)
  • function – the function to be executed after the given delay period
  • delay – the time, in milliseconds, the timer should wait before executing the function. This is an optional argument. If it is not specified, a default value of 0 is used.
  • arg1, arg2, ... argN – arguments for the given function. This is also optional.

The setTimeout the method returns an integer value that identifies the timer that is created. This integer is used to clear the timer as we will see soon.

Let’s use an example now

Basic setTimeout example

function sayHello() {
    alert("Hello")
}

setTimeout(sayHello, 2000)

This will alert “Hello” after 2 seconds.

If this sayHello the function accepts arguments, we can do this:

function sayHello(name) {
    alert(`Hello, ${name}`)
}

setTimeout(sayHello, 1000, "Sarah")

This will alert “Hello, Sarah” after 2 seconds.

Oh! Don’t we just hate browser alerts? Let’s move on to a related and important method that we can use to prevent the function from executing.

clearTimeout

The clearTimeout a method is used to cancel the timer. For instance, we may want to cancel the timer before it executes the function. Remember that the setTimeout method returns an ID. This ID is used to cancel the timer. Let’s do this:

function sayHello(name) {
    alert(`Hello, ${name}`)
}

const timerID = setTimeout(sayHello, 3000, "Sarah")

clearTimeout(timerID)

The timer will never run.

Let’s move on to our next method.

setInterval

The setInterval method is used to schedule a function to be executed repeatedly after a period of time. The syntax for this method is this:

const timerID = setInterval(function, delay, arg1, arg2, ...)

In this case, the delay is the time in milliseconds that the timer should delay successive executions of the function. The setInterval method also returns an ID which is used to clear the timer.

Notice that its syntax is very similar to that of the setTimeout. However, take note of this difference. For the setTimeout method, the function is only fired once after the timer has expired. However, the setInterval method runs the function repeatedly unless it is canceled. Let’s use an example.

function sayHello(name) {
    console.log(`Hello, ${name}`)
}

setInterval(sayHello, 3000, "Sarah")

The code above will repeatedly print “Hello Sarah” to the console after 3 seconds. Try to run the code to confirm this.

To stop the setInterval from continuously running, we use the clearInterval method.

clearInterval

The clearInterval method is used to stop the execution of a setInterval method. It accepts a timer ID as argument and uses the ID to stop the timer.

Let’s go back to our example.

let counter = 0;
function sayHello(name) {
    alert(`Hello, ${name}`)
    counter++;

    if (counter === 3) {
        clearInterval(timerID)
    }
}

let timerID = setInterval(sayHello, 3000, "Sarah");

The function sayHello will be executed only 3 times.

You may wonder why the if statement is inside the function and not outside the function like this:

let counter = 0;
function sayHello(name) {
    alert(`Hello, ${name}`)
    counter++;
}

let timerID = setInterval(sayHello, 3000, "Sarah")

if (counter === 3) {
    clearInterval(timerID)
}

At this point, we need to understand the way JavaScript executes the setInterval and setTimeout methods.

Non-blocking I/O Operations

Unlike other languages, JavaScript has a single thread for executing tasks and it executes tasks this line by line. Meaning one line of code must complete execution before moving on to the next. In other words, the execution of JavaScript code is blocked.

However, there are some non-blocking I/O operations that are handled by the underlying engine. Operations such as fetching data via Ajax, setTimeout and setInterval belong to this category. So JavaScript does not wait for the function(callback function) passed to the setTimeout or setInterval method to finish executing before it moves on to the next task or line of code.

In the example above, if we had written it the second way, the timer will not stop running. This is because immediately after executing this line let timerID = setInterval(sayHello, 3000, "Sarah"), Javascript moves on to the next code block which is

if (counter === 3) {
    clearInterval(timerID)
}

And at that point, the condition is not true, so the timer is never cleared. This is also the reason why in our clearTimeout example, the callback function passed to the setTimeout is never triggered. Because JavaScript immediately moved on to the next line of code.

Thank you for reading

JavaScript Tags:Javascript

Post navigation

Previous Post: How to remove index.php from URL in CodeIgniter 4
Next Post: How to check the PHP version

Related Posts

  • How to Reverse A String with JavaScript
  • How to use the Local Storage in Javascript
  • How to fix getFullyear() is not a function with JavaScript?
  • How to Object Destructuring in ES6
  • How to trigger a button click from another button click event with JavaScript?
  • Best JavaScript Minifying Tools

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Codeigniter (3)
  • CSS (11)
  • eCommerce (1)
  • Framework (1)
  • Git (3)
  • How to (43)
  • HTML (5)
  • JavaScript (15)
  • Jquery (7)
  • Laravel (1)
  • Linux (4)
  • Magento-2 (1)
  • Node js (4)
  • Others (2)
  • PHP (11)
  • React (13)
  • Server (1)
  • SSH (3)
  • Symfony (6)
  • Tips (16)
  • Top Tutorials (10)
  • Ubuntu (3)
  • Vue (1)
  • Wordpress (7)

Latest Posts

  • What is SSH in Linux?
  • How to Delete Files in Ubuntu Command Line
  • How to Deploy a React application on a cPanel
  • How to use events listeners and Event Subscriber in Symfony
  • How to Convert PHP CSV to JSON

WEEKLY TAGS

AJAX (1) Codeigniter (1) Javascript (11) JQuery (1) PHP (16) Programming (1) React (3) Symfony (1)

Random Post

How to check the PHP version
How to trigger a button click from another button click event with JavaScript?
How to Make Toggles With React Hooks
How to Object Destructuring in ES6
Enable or Disable SSH Root Login Access in Linux

Quick Navigation

  • About
  • Contact
  • Privacy Policy

© Teach Developer 2021. All rights reserved