setTimeout() works with intuitive code examples.
setTimeout() method syntax is as follows:
The first parameter of the
function that you want to execute. You can write the
function directly when passing it, or you can also refer to a named function as shown below:
Next, you can pass the
One second is equal to one thousand milliseconds, so if you want to wait for 3 seconds, you need to pass
3000 as the second argument:
If you omit the second parameter, then
setTimeout() will immediately execute the passed
function without waiting at all.
Finally, you can also pass additional parameters to the
setTimeout() method that you can use inside the
function as follows:
Now you may be thinking, "why not just pass the parameters directly to the function?"
This is because if you pass the parameters directly like this:
setTimeout(greeting("Nathan", "Software developer"), 3000);
function without waiting, because you're passing a function call and not a function reference as the first parameter.
This is why if you need to pass any parameters to the function, you need to pass them from the
But honestly, I never found the need to pass additional parameters to the
setTimeout() method in my role as a Software Developer, so don't worry about it 😉
How to Cancel the setTimeout Method
You can also prevent the
setTimeout() method from executing the
function by using the
clearTimeout() method requires the
id returned by
setTimeout() to know which
setTimeout() method to cancel:
Here's an example of the
clearTimeout() method in action:
If you have multiple
setTimeout() methods, then you need to save the IDs returned by each method call and then call
clearTimeout() method as many times as needed to clear them all.
setTimeout() method is a built-in method that allows you to time the execution of a certain
function . You need to pass the amount of time to wait for in
milliseconds , which means to wait for one second, you need to pass one thousand
To cancel a
setTimeout() method from running, you need to use the
clearTimeout() method, passing the ID value returned when you call the
Thanks for reading this tutorial