Table of Contents
setTimeout to wait 5 seconds
setTimeout method we can delay some code to some specified time (say 5 seconds). The
setTimeout method executes your code after the set
delay expires. This global method works as an asynchronous method that will not pause the execution of other functions within the function stack.
setTimeout method takes two main parameters -
delay - to execute your code after a set time. The
code parameter (a function that could be anonymous) is required, but the
delay parameter is optional (and the default value is 0). We can have other additional parameters which are passed through to the function that we passed.
setTimeout(code, delay, arg1, ..., argN)
code, as stated earlier, is a function (a callback function) that will contain code that we want to wait for a while before executing. The
delay serves as the amount of time that we will wait the code for which is defined in milliseconds.
wait effect, we will run other functions after the
multiply function result is logged first then the
greetUser, and this is because these two functions are run synchronously within the function stack (from top to bottom). However, the
printJS function that was present before
greetUser function is returned after them, and that’s due to the use of the
setTimeout at 1500 milliseconds (1.5 seconds). Finally, the anonymous function passed to the
setTimeout method at 5000 milliseconds (5 seconds) is returned last. So, with the aid of the
setTimeout method which allows us to pass a function (or an anonymous function) and the delay parameter that will help define for how long we delay a code section.