×

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code.

setTimeout() is an asynchronous function, which means that it will not interrupt the execution of other functions in the stack. To put it another way, setTimeout() cannot be used to create a "pause" before the next function in the function stack executes.

After a specified number of milliseconds, the setTimeout() method runs a function.

1000 milliseconds is equal to 1 second

Syntax

setTimeout(function, milliseconds, param1, param2, param3 ...)

Parameter Values

  function  Required  After the timer has expired, this function will be run.  
  milliseconds  Optional  The timer should wait in milliseconds before the provided function or code is run. If this option is left blank, a value of 0 is used, which means that the event will be executed "immediately," or more precisely, during the next event cycle. It's worth noting that the real delay may be longer than planned in any situation.  
  param1, param2, param3 ...  Optional  Additional parameters are given through to the function that the function specifies.  

Return Value

The timeoutID value returned is a positive integer that identifies the timer generated by the setTimeout() function. To cancel the timeout, provide this value to clearTimeout().

A timeoutID value will never be reused by a call to setTimeout() or setInterval() on the same object in the future. Different objects, on the other hand, have their own sets of IDs.

Example

 setTimeout(() => {console.log("this is the first message")}, 5000);
  setTimeout(() => {console.log("this is the second message")}, 3000);
  setTimeout(() => {console.log("this is the third message")}, 1000);

It's worth noting that the first function does not call the second function after a 5-second "pause." Instead, the first function is called, but it is not executed for another 5 seconds. The second function is called while the first function is waiting to execute, and it is given a 3-second delay before it executes. The third function is invoked and completes its execution first, when neither the first nor the second function's timers have finished. After the first function's timer expires, the first function is ultimately performed.

Important

  • The setTimeout() method is only used once.
  • SetInterval() should be used instead if you require several executions.
  • To prevent the function from beginning, use the clearTimeout() method.
  • Use the id returned by setTimeout() to clear a timeout:
myTimeout = setTimeout(function, milliseconds);
  • Then you may to halt the execution by calling
clearTimeout(myTimeout); 

Example 1:

Note that the setTimeout() function is handy when you wish to run a piece of code once after a certain amount of time has passed. For example, displaying a message to a user when a certain amount of time has passed

function welcome() {
    console.log('Welcome to TutorialAndExample!');
}


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

Output

This message is shown first
Welcome to TutorialAndExample!

After 3000 milliseconds, the setTimeout() method in the preceding software invokes the welcome() function (3 seconds). As a result, after 3 seconds, the application only shows the message 'Welcome to TutorialAndExample!' once.

Example 2:

A clock that is made up of timing events:

function startTime() {
  const date = new Date();
  document.getElementById("txt").innerHTML = date.toLocaleTimeString();
  setTimeout(function() {startTime()}, 1000);
}

Related Topics

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 minutes read.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.