开发者

Delay the return of a function

开发者 https://www.devze.com 2023-03-12 12:21 出处:网络
Is there anyway to delay the return of a function using setTimeout()? function foo(){ window.setTimeout(function(){

Is there anyway to delay the return of a function using setTimeout()?

function foo(){
  window.setTimeout(function(){
      //do something
  }, 500);
 //return 开发者_StackOverflow社区"something but wait till setTimeout() finishes";
}


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


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);
  });
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号