延迟函数的返回

问题描述 投票:7回答:4

无论如何使用setTimeout()来延迟函数的返回。

function foo(){
  window.setTimeout(function(){
      //do something
  }, 500);
 //return "some thing but wait till SetTimeout() finished";
}
javascript delay settimeout
4个回答
3
投票

您不希望“延迟”代码,因为它会锁定浏览器线程,使您的整个浏览器无法使用,直到您的脚本超时为止。

你可以设置一个事件来监听一段时间过后发出的信号。 jQuery .bind().trigger()是你想要的http://api.jquery.com/trigger/

或者,您可以使用回调函数在时间过去之后处理所需的数据。所以如果你想要这样:

function myFunc() {
  doStuff();
  result = delayProcess(5000);
  $('#result').html(result);
}

function delayProcess(delay) {
  // magic code that delays should go here
  return logic;
}

应该是这样的:

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

2
投票

.setTimeout()用于在超时后运行完整的函数。它不是为了延迟代码。

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

一个很好的联系是:What is the JavaScript version of sleep()?

(一个很好的问题是为什么你需要你的功能睡觉?)


1
投票

只需在超时功能结束时超时后调用您想要发生的事情,如下所示:

function foo()
{ 
    window.setTimeout(function()
    { 
        //do something

        delayedCode(returnValue); 
    }, 500); 

    return
}

function delayedCode(value)
{
    // do delayed stuff
}

而不是返回。将依赖返回值的代码放入delayedCode()并将参数传递给函数。


1
投票

使用承诺:

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

回答更新,感谢@NikKyriakides,他们指出async / await不是必需的。我最初有async () => resolve(await apiCall())

© www.soinside.com 2019 - 2024. All rights reserved.