【问题标题】:setTimeout and promise设置超时和承诺
【发布时间】:2016-12-02 19:12:39
【问题描述】:

我需要获取数据,这可能需要一些时间。如果需要超过 100 毫秒,我想显示一个加载器。这就是我所做的

fetchOptions(value, page = 0){
    return new Promise((resolve, reject) => { ... });
}

getOptions(text, page = 0) {
    if (this.requestTimeout) clearTimeout(this.requestTimeout);
    this.requestTimeout = setTimeout((()=>{
      console.log("!!");
    }), 100);

this.fetchOptions(text, page)
      .then(data => {
        //do something
        //if (this.requestTimeout) clearTimeout(this.requestTimeout);
      })
      .catch(e => console.log(e));
 }

fetchOptions 工作 5 秒,因为它包含类似的功能

sleep(ms) {
    var unixtime_ms = new Date().getTime();
    while(new Date().getTime() < unixtime_ms + ms) {}
}

(因为我想测试长获取过程)。

因此,console.log 仅在 promise 解决后才被调用。我真的需要帮助来了解它为什么会发生以及如何解决这个问题

【问题讨论】:

  • while(new Date().getTime() &lt; unixtime_ms + ms) {} 会阻止程序、您的计时器、用户以及您网站上的所有其他内容。不要这样做。
  • @tcooc 是对的。您最好在 sleep 方法的超时中使用带有 resolve 的 promise。像这样: sleep (ms) { return new Promise((resolve, reject) => { setTimeout(resolve, 5000); }) }
  • 谢谢你们,这确实有道理。现在感觉自己真的很愚蠢:)

标签: javascript reactjs promise settimeout


【解决方案1】:

CSS 是一种选择吗?您可以立即设置一个类并使用动画来延迟效果。

document.querySelector('button').addEventListener(
  'click',
  () => document.querySelector('div').classList.toggle('effect'),
  false);
.effect { 
  background-color:red; 
  animation: effect 500ms forwards;
  border:1px solid black;
  }

@keyframes effect {
    0% {background-color:transparent;}
    99% { background-color:transparent; }
    100% {background-color:red;}
}
<button type='button'>Toggle Class</button>
<div>result</div>

【讨论】:

  • 感谢您的建议。恐怕在我的特殊情况下这会让人头疼,但这是一个非常漂亮的主意!
猜你喜欢
  • 2020-03-17
  • 2014-03-21
  • 1970-01-01
  • 2015-07-09
  • 2018-09-04
  • 2020-07-19
  • 1970-01-01
  • 2019-07-07
  • 1970-01-01
相关资源
最近更新 更多