YogeshChauhan.com

Window setTimeout() Method in JavaScript

March 29, 2021

Ever wondered what to use to execute a set of action after a certain time? setTimeout Method is the answer.

Do not get confuse with setInterval method. The difference is setInterval methods repeats a set of code after the wait and setTimeout just waits for the specified time and executes the code once.

We can specify milliseconds in setTimeout method.

Here’s the complete syntax for setTimeout() Method



setTimeout(function, interval, args...)


Where function(required) is nothing but JS code as a function. IE 4 and earlier versions don’t support this parameter.

interval is required and we can pass milliseconds.

In args (optional) parameters we can pass any number of parameters. Not supported in IE 9 and earlier versions.

So, we can rewrite the syntax like this:



setTimeout(code, interval)


What does it return?

Well the execution has to stop. So, it returns a value that we can pass to Window.clearTimeout( ) which then can be used to cancel the execution of the supplied code or function.

We must use a variable when creating the setTimeout method to stop the timer using the clearTimeout method.

setTimeout() Method Examples

You can use a seperate function or add the function inside setTimeout method.

Here are both ways to do it.

In the first example above, we can use this code to stop the timer execution.



clearTimeout(example);


How to pass parameters in setTimeout()?

Here’s how:

The above method doesn’t work in in IE9 and earlier!

Use this anonymous function instead for all browsers compatibilty:

dreamhost

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

How to Draw a Circle in HTML5 Using Canvas Tag?HTMLIs monitoring an employee’s work on a computer a desirable or undesirable activity?MiscHow to check if the element exists using JavaScript and jQuery?JavaScript4 different Ways to Get JavaScript OutputJavaScriptHow to make WordPress main stylesheet (style.css)?WordPressHow to add Go Back button in Swift 5?Swift