Function Return Delay

in any case, you must defer the return of the function using setTimeout() .

 function foo(){ window.setTimeout(function(){ //do something }, 500); //return "some thing but wait till SetTimeout() finished"; } 
+7
source share
4 answers

You don’t want to β€œdelay” the code because it blocks the browser flow, making your browser inoperative until your script timeout expires.

You can configure events that listen to a signal that has passed after a while. jQuery .bind() and .trigger() are what you want http://api.jquery.com/trigger/

Or you can use the callback function to work with the data you want after being ellapsed. So, if you intended to be like this:

 function myFunc() { doStuff(); result = delayProcess(5000); $('#result').html(result); } function delayProcess(delay) { // magic code that delays should go here return logic; } 

There should be something like this:

 function myFunc() { doStuff() delayProcess(5000, function(result){ // Notice the callback function pass as an argument $('#result').html(result); }); } function delayProcess(delay, callback) { result = logic; setTimeout(function(){ callback(result); }); } 
+3
source

.setTimeout() designed to run the full function after a timeout. not to delay code.

https://developer.mozilla.org/En/Window.setTimeout

Good link: What is the JavaScript version for sleep ()?

(Good question, why do you need your sleep function?)

+2
source

Just call what you want after the timeout at the end of the timeout, as shown below:

 function foo() { window.setTimeout(function() { //do something delayedCode(returnValue); }, 500); return } function delayedCode(value) { // do delayed stuff } 

Instead of returning. Put the code that relies on the return value in delayedCode() and pass the parameter to the function.

+1
source

Using promises:

 const fetchData = () => new Promise(resolve => ( setTimeout(() => resolve(apiCall()), 3000); )); 

Answer updated by @NikKyriakides, who pointed out that async / await is optional. I initially had async() => resolve(await apiCall()) .

0
source

All Articles