Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a period of time after a function run

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.)

like image 363
Mellon Avatar asked Nov 15 '11 09:11

Mellon


People also ask

How do you make a function wait for some time?

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() .

How do you make a function wait for a second?

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.

How do you delay a function execution?

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.


1 Answers

Just put your code inside an anonymous function passed to setTimeout.

e.g.

functionToRunFirst(); setTimeout(function() {     // rest of code here }, 2000); 
like image 141
GregL Avatar answered Sep 23 '22 13:09

GregL