Javascript setTimeout

Sometimes you might want to delay the execution of your code.

You may need certain lines of code to execute at a point in the future, when you explicitly specify, rather than all the code executing synchronously.

Something like that is possible with JavaScript. The general syntax for the setTimeout() method looks like this:

setTimeout(function_name, time);

Let’s break it down:

  • setTimeout() is a method used for creating timing events. It accepts two required parameters.
  • function_name is the first required parameter. It is the name of a callback function that contains the code you want to execute. The name of the function acts as a reference and pointer to the function definition that contains the actual block of code.
  • time is the second required parameter, and it is defined in milliseconds (for reference, 1 second = 1000 milliseconds). It represents the specified amount of time the program has to wait for the function to be executed.

Here is an example;

function TranStatusCheck() { alert ('hi') }
$(function(){
    //run above method once after 1ms
    window.setTimeout(TranStatusCheck, 100);    //100ms (1000 ms = 1 sec)
});

Remember, not to write method this way;

window.setTimeout(TranStatusCheck(), 100);

Reference

https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

https://javascript.info/settimeout-setinterval

https://www.freecodecamp.org/news/javascript-wait-how-to-sleep-n-seconds-in-js-with-settimeout/

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect