In this article, all the details behind the concept and working of the function “setTimeout()” are explained.
What is the objective behind setTimeout()?
Everyone in their lives has made use of a gadget called a timer. Timers or an alarm are used for many various procedures. A timer provides the functionality of knowing when to stop or start certain actions in your daily life. Much like that, the “setTimeout()” function will provide this feature to your code. Using this function will provide delays before any user-defined functions can be executed.
Let’s take an example of this. In a video game, the enemy has to respawn exactly 20 seconds after it is killed. The “setTimeout()” function will be implemented into the original code which is responsible for running the videogame. This function is what will cause the enemy to have a 20-second delay before it spawns again. In the same game, this function can be used for something very contrasting. Suppose an item has appeared for the player. But the game developer does not want that item to linger around for infinity. This is where the “setTimeout()” will step in and give a limited time for that item to linger.
How does the setTimeout() function work?
This syntax is very basic and easy to understand. It takes two parameters within its brackets. The first parameter is the user-defined function that is to be executed. We will take another parameter which is the time of the delay(milliseconds) that will occur before the user-defined function is executed. Below is a sample code for this execution:
alert("Timer has run out!");
In this example, the function “sampleFunction” will be executed 5 seconds(5000 milliseconds) after the code is run. Refer to the snippet below:
There are a few other details to note about this code as well.
- The default delay time is 0.
- The function returns will return the id of the timer.
- Additional functions can also be passed in versions after “IE9”