×

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 Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 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 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 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.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 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.

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.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

Javascript Tutorial

JavaScript is a light-weight, dynamic scripting language that is mainly employed to create interactive front-end web applications. It was originally developed in 1995 by Brendan Eich at Netscape Communications Corporation...

5 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.

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 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.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.

Javascript Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 minutes read.

Javascript Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 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.

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.