×

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 Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 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 If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

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

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.

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

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

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 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 Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

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

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