简体   繁体   English

setTimeout和Promise

[英]setTimeout and promise

I need to fetch data, and it could take some time. 我需要获取数据,这可能需要一些时间。 If it takes more than 100ms I want to show a loader. 如果需要100毫秒以上的时间,我想显示一个加载程序。 This is what I did 这就是我所做的

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 works for 5 seconds cause it contains a function like fetchOptions可以工作5秒钟,因为它包含如下功能

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

(because I wanted to test long fetching process). (因为我想测试较长的提取过程)。

As a result console.log is called only after promise resolved. 结果,仅在承诺解决后才调用console.log I really need a help to understand why does it happen and how to solve this problem 我真的需要帮助来了解为什么会发生以及如何解决此问题

Is CSS an option? CSS是一种选择吗? You can set a class immediately and use animations to delay the effect. 您可以立即设置一个类,并使用动画来延迟效果。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM