JavaScirpt Tutorial Index

JavaScript Tutorial Javascript Example Javascript comment Javascript Variable Javascript Data Types Javascript Operators Javascript If Else Javascript Switch Statement Javascript loop JavaScript Function Javascript Object JavaScript Arrays Javascript String Javascript Date Javascript Math Javascript Number Javascript Dialog Box Javascript Window Object Javascript Document Object Javascript Event Javascript Cookies Javascript getElementByID Javascript Forms Validation Javascript Email Validation Javascript Password Validation Javascript Re-Password Validation Javascript Page Redirect Javascript Print

Misc

JavaScript P5.js JavaScript Minify JavaScript redirect URL with parameters Javascript Redirect Button JavaScript Ternary Operator JavaScript radio button checked value JavaScript moment date difference Javascript input maxlength JavaScript focus on input Javascript Find Object In Array JavaScript dropdown onchange JavaScript Console log Multiple variables JavaScript Time Picker Demo JavaScript Image resize before upload Functional Programming in JavaScript JavaScript SetTimeout() JavaScript SetInterval() Callback and Callback Hell in JavaScript Array to String in JavaScript Synchronous and Asynchronous in JavaScript Compare two Arrays in JavaScript Encapsulation in JavaScript File Type Validation while Uploading Using JavaScript or jquery Convert ASCII Code to Character in JavaScript Count Character in string in JavaScript Get First Element of Array in JavaScript How to convert array to set in JavaScript How to get current date and time in JavaScript How to Remove Special Characters from a String in JavaScript Number Validation in JavaScript Remove Substring from String in JavaScript

Interview Questions

JavaScript Interview Questions

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);
}