Javascript - How to use setTimeout to run a function after some time

In Javascript you can use setTimeout to set a time for a function to be triggered, it will only be triggered once. If you want to run a function after three seconds you can do the following:

setTimeout(function(){
   console.log('this is triggered after three seconds'); 
}, 3000);

The first parameter is the function you want to execute, the second is the amount of time in milliseconds to wait before executing the function. This is not blocking and thereby asynchronous (it is not running concurrently on a separate thread), this can be seen below where the second setTimeout will be triggered first as it is set to trigger only after one second, whereas the first after three seconds.

setTimeout(function(){
   console.log('this is triggered after three seconds'); 
}, 3000);

setTimeout(function(){
   console.log('this is triggered after one second'); 
}, 1000);

You can stop a setTimeout function by using the clearTimeout function which takes the timeoutId of the setTimeout function as seen below:

let timeoutId = setTimeout(function(){
   console.log('this is triggered after three seconds'); 
}, 3000);

clearTimeout(timeoutId);

If you want to run the function in an interval rather than only once, you should look into setInterval. These are the most important things to know about setTimeout!

That is all

I hope you found this short post helpful, please leave a comment down below with your thoughts!