过滤数据并显示加载器,但先是浏览器冻结,然后显示加载器并立即消失,异步功能不起作用

Filtering data and showing loader, but first the browser freezes, then the loader is shown and immediately disappears, async function doesn't work

提问人:Marko 提问时间:9/18/2023 更新时间:9/18/2023 访问量:13

问:

我想在用户单击搜索时显示加载器,但我对屏幕加载器有问题,或者更确切地说是 JavaScript 单线程的性质有问题。即使我在过滤之前放置加载器,浏览器也没有机会更新 UI。单击按钮,然后浏览器等待 2-4 秒(冻结),然后过滤数据,然后加载器显示半秒钟并消失。如何解决问题,以便在数据开始过滤之前单击按钮时显示加载器,并且我的浏览器不会冻结?

我用 Promise 尝试过这样,但它不起作用。我找到了一些将我的代码转换为异步的例子,但它们都没有帮助,即使有微小的延迟显示加载器不起作用。这是我尝试的最后一个例子。 我正在使用这个加载器库 https://gasparesganga.com/labs/jquery-loading-overlay/

//function for filtering
function filter(searchSplit) {

$('.parent').LoadingOverlay("show");
var button = $(this);
button.attr('disabled', true);

new Promise((resolve, reject) => {
    setTimeout(function () {
    
        $(".table tbody tr").not(":containsi('" + searchSplit + "')").each(function (e) {
            $(this).attr('visible', 'false');
            if (!$(this).parents('.parentEl').hasClass('.foundParentEl')) {
                $(this).parents('.parentEl').addClass('hide');
            }
            if (searchSplit.length > 4) {
                $(this).parents('.list').removeClass('show');
            }
        });

        $(".table tbody tr:containsi('" + searchSplit + "')").each(function (e) {
            $(this).attr('visible', 'true');
            $(this).parents('.parentEl').removeClass('hide');
            if (searchSplit.length > 4) {
                $(this).parents('.list').addClass('show');
            }
        });

        var empty = $(".table tbody").not(':has(tr)');

        if (searchSplit.length > 4) {
            empty.parents('.parentEl').addClass('hide');
        }
        else {
            empty.parents('.parentEl').removeClass('hide');
        }

        if (searchSplit.length > 4) {
            $(window).trigger('resize');`your text`
        }

        resolve();  
    }, 0);
})
.then(() => {
    // This will run after your code is done
    button.attr('disabled', false);
    $('.parent').LoadingOverlay("hide");
});`


}

//click event on button
$('.btn-search').click(function () {
    var searchTerm = $(".search").val();
    var searchSplit = searchTerm.replace(/ /g, "'):containsi('");
    filter(searchSplit); //calling function
});
JavaScript jQuery 异步 搜索 加载器

评论


答: 暂无答案