Delay the return of a function
Solution 1
Using promises:
const fetchData = () =>
new Promise(resolve => {
setTimeout(() => resolve(apiCall()), 3000);
});
Answer updated thanks to @NikKyriakides who pointed out async/await is not necessary. I initially had async () => resolve(await apiCall())
.
Solution 2
You don't want to "delay" the code, because it would lock up the browser thread making your entire browser unusable until the your script's timeout has passed.
You can either set up an events which listens to a signal fired up after some time has passed. jQuery .bind()
and .trigger()
is what you want http://api.jquery.com/trigger/
Or, you could use a callback function to work with the data you want after the time has ellapsed. So if what 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;
}
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);
});
}
Solution 3
.setTimeout()
is for running a complete function after a timeout. It is not for delaying code.
https://developer.mozilla.org/En/Window.setTimeout
A good link would be: What is the JavaScript version of sleep()?
(A good question to ask is why do you need your function to sleep?)
Solution 4
Just call the thing you want to happen after the timeout in the end of the timeout function as below:
function foo()
{
window.setTimeout(function()
{
//do something
delayedCode(returnValue);
}, 500);
return
}
function delayedCode(value)
{
// do delayed stuff
}
Rather than returning. Put the code that relies on the return value into delayedCode()
and pass in the parameter to the function.
khousuylong
Updated on August 01, 2022Comments
-
khousuylong almost 2 years
Is there anyway to delay the return of a function using
setTimeout()
?function foo(){ window.setTimeout(function(){ //do something }, 500); //return "something but wait till setTimeout() finishes"; }
-
RobG about 13 yearsThat's the same as calling setTimeout from myFunc, except that in the above result becomes a global variable the moment something is assigned in the delayProcess function.
-
nicholaswmin over 5 yearsYou don't need to
async/await
. Just:setTimeout(() => resolve(apiCall()), 3000);
-
Nelu over 5 yearsYou're right @NikKyriakides! Thank you. Will update my answer.
-
Nathan about 5 yearsnew Promise(resolve => { setTimeout(() => resolve(apiCall()), 3000); }); Corrected typo with missing parenthesis.