codewithjohn.dev
Published on

Understanding the setTimeout Function In Javascript

In this Article, you will learn about the JavaScript built-in setTimeout() method with the help of examples.

Sometimes We may want to execute a function not right now but at a certain time later, or simply schedule the call". You can think of The setTimeout() method executes a block of code after the specified time. Unlike the setInterval method, this method executes the code only once.

Syntax

setTimeout(func, delay, arg1, arg2, ...)

Parameters

  • func: a function containing a block of code to be executed after the specified delay.

  • delay: (Optional) The duration in milliseconds to wait before the function or code is executed if the value is not specified then setTimeout() will immediately execute the passed function without waiting at all.

  • arg1, arg2, ...: (Optional) Any additional arguments to be passed to the function.

Return value

The setTimeout() method returns an timeoutID which is a positive integer. This ID is an integer value that can be passed as an argument to the clearTimeout() function to stop the execution.

Here's an example that displays a Text After 3 Second

example_one.js
function seyHello() {
  console.log('Hello')
}

setTimeout(seyHello, 3000)
console.log('This message is shown first')

In the above program, the setTimeout() method calls the seyHello() function after 3000 milliseconds (3 second).

As we mentined above If you log the value of setTimeout() method it returns an timeoutID which is a positive integer For example.

example_two.js
function seyHello() {
    console.log("Hello"); // Hello
}

let intervalId = setTimeout(seyHello, 3000);
console.log('Id: ' + intervalId); // Id: 2

We can use setTimeout() with arguments let's us assign as many arguments as necessary to the callback function. For example, let's say we want to log Hello John with a custom message. We simply append arguments to the end of the setTimeout parameter list Here's an example

example_three.js

function seyHello(message, user) {
 console.log(`${message} ${user}`);
}

setTimeout(seyHello, 3000, "Hello", "John"); // Hello John

In the above example, two parameters Hello and John passed to the setTimeout() method. These two parameters are the arguments that will be passed to the function seyHello() that is passed to the setTimeout() method.

JavaScript clearTimeout()

You can also cancel the setTimeout() method from executing the function. by using the clearTimeout() method. In the above section, we mentioned that the setTimeOut() function returns an id, which is an integer. We can pass the id to the clearTimeout() function, which requires the id returned by setTimeout() to know which setTimeout() method to cancel. The clearTimeout() method cancels the setTimeout() method call before it happens.

example_three.js

const timeoutId = setTimeout(function(){
    console.log("Hello");
}, 3000);
clearTimeout(timeoutId);
console.log(`Timeout ID ${timeoutId} has been cleared`); // Timeout ID 2 has been cleared

In the above program, the setTimeout() method is used to log hey after 3 seconds. However, the clearTimeout() method stops the function call of the setTimeout() method.

Conclusion

In this article, you have learned about the JavaScript setTimeout() method, which is a built-in method that allows you to schedule the execution of a certain function. You can cancel a setTimeout() method from running by using the clearTimeout() method and passing the ID value returned when you call the setTimeout() method.

Further Reading

For a deeper understanding of the setTimeout() and clearTimeout() functions, you may explore the comprehensive documentation provided by the Mozilla Developer Network (MDN):

Visit the MDN page on setTimeout() for detailed insights into the setTimeout() function, including usage, syntax, and examples.

Similarly, the MDN page on clearTimeout() offers valuable information on the clearTimeout() function.

If you're interested in periodic execution of tasks, you might also want to explore the setInterval().