If I have a function which I would like my js code to run it immediately but after the run, wait for 2 seconds. How to achieve this logic?
(Note: It is just the inverse logic compare with setTimeout()
, since setTimeout(
) first wait a certain amount of time then execute the function.)
Use setTimeout() to run a function after a single delay, and cancel that delay at any time with clearTimeout() . Use setInterval() to run a function many times with a delay before each execution, and cancel those repeated executions with clearInterval() .
To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.
To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.
Just put your code inside an anonymous function passed to setTimeout.
e.g.
functionToRunFirst(); setTimeout(function() { // rest of code here }, 2000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With