如果循环时间较长,如何执行函数?

问题描述 投票:0回答:1

我有一个AJAX调用,结果由回调处理。这可能很快,也可能需要一些时间。如果回调持续超过 3 秒,我想显示一个图像(或文本)告诉用户“请稍候!”。

这就是我所拥有的:

var process_timer, is_processing = false;
var request = createCORSRequest();
if (request) {
    // This SETTIMEOUT function should execute 3 seconds after REQUEST.SEND()
    process_timer = setTimeout(function(){
        if (is_processing) {
            // It's still processing, so we show the message
            show_please_wait();
        }
    },3000);
    request.onload = function() {
        process(JSON.parse(request.responseText));
        // OK, processing is done, so we reset everything
        is_processing = false;
        // If SETTIMEOUT didn't fire yet, we cancel it so no image will ever show
        clearTimeout(process_timer);
        // We hide the message anyway, just in case it was displayed
        hide_please_wait();
    };
    is_processing = true;
    request.send();
}

发生了什么:

  • REQUEST.SEND() 工作正常
  • REQUEST.ONLOAD() 工作正常
  • ...但是 SHOW_PLEASE_WAIT() 函数永远不会被执行,无论进程持续多久。 我做错了什么?
javascript settimeout
1个回答
0
投票

使用全局变量来保持承诺的状态是有问题的。特别是当可能有多个异步进程需要等待时。

以下演示如何展示

const waitDiv=document.getElementById("wait");
async function delayedFetch(url,ms) {
  console.log("show waitDiv after 2000ms");
  const timeout=setTimeout(()=>waitDiv.classList.remove("hidden"),2000);
  await new Promise(r=> setTimeout(r,ms)).then(()=>console.log("delay is over"));
  console.log(`call fetch after ${ms} milliseconds`);
  const data=fetch(url).then(r=>r.json());
  clearTimeout(timeout);
  waitDiv.classList.add("hidden");
  return data;
}

delayedFetch("https://dummyjson.com/users/2",5000).then(u=>
 console.log(`all done, user name is: ${u.firstName} ${u.lastName}`)
)
.hidden {display:none}
<div id="wait" class="hidden">please wait ... this is taking longer!</div>

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