如何显示一个繁忙的指示器长非ajax操作

How to show a busy indicator for a long non-ajax operation?

本文关键字:指示器 操作 ajax 一个 何显示 显示      更新时间:2023-09-26

我有一个在客户端上运行2-3秒的函数(没有ajax调用)。当这个操作正在运行时,我试图显示一个"繁忙/正在处理"动画。

简化代码如下:

var ajaxContainer = $('.spinner');
// show
$(ajaxContainer ).show();
// long operation
var items = GetItems();
$.each(items, function (index, value) {
    ProcessItem(value.itemID);
});
// hide
$(ajaxContainer ).hide();

,但这并没有像预期的那样工作。我得到的结果是操作运行时没有显示旋转器。尽管它确实显示操作何时结束。

我在网上看到一些帖子提到这可以通过使用windows.setTimeout()来完成。但是,由于此操作是基于动态数量的项,因此我不希望提前设置特定的超时数。相反,我想在操作开始时显示旋转器,并在操作完成时隐藏它。

是否有一种优雅的方式来实现这一点?

我认为你必须为ProcessItem函数添加一个回调参数,以便检查是否所有项都已处理。试试这样:

function ProcessItem(id, callback){
    //do process and after call callback function 
    callback(); 
}
var processedItemsQuantity = 0;
var ajaxContainer = $('.spinner');
ajaxContainer.show();
// long operation
var items = GetItems();
$.each(items, function (index, value) {
    ProcessItem(value.itemID, function(){ 
        if (items.length - 1 == processedItemsQuantity){
            ajaxContainer.hide();
        } 
        else processedItemsQuantity++;
    });
});

你不能在同步操作中显示旋转器,因为它阻塞了UI (ajax是异步的,这就是它工作的原因)。

你需要的是把你的代码放到一个Web Worker中。