将 setTimeout 合并到 jQuery .each 中

Incorporate setTimeout Into jQuery .each

本文关键字:each jQuery setTimeout 合并      更新时间:2023-09-26

以下代码从 URL 请求 json 数据。 获得该数据后,它会为 json 数据中的每个元素运行一个 .each 函数。 为了举例起见,我将 .each 函数简化为简单地使用 json 中的每个值执行 document.write,并在结束后提醒"已完成"。

如果我删除 setTimeout,那么代码将按预期工作,首先完成所有 .each 命令,然后发出警报。 但是,使用 setTimeout,它会在执行所有 .each 命令之前发出警报。

我让延迟本身完美运行,但是初始延迟后的代码会立即执行,而不是等待所有 .each 命令执行。 这是代码:

$.ajax({
            type: "GET",
            url: 'url to json data',
            dataType: "json",
            success: function(data) {
            var time = 10;
                $.each(data, function(key, val) {
                setTimeout(function() {
                document.write(val.term);
                   return;
                }, time); time += 10;
                });
            alert('finished');
            },
            error: function () {}
        })

如何在遍历 .each 命令时保持延迟,并且只有在遍历完所有 .each 命令时才发出警报"已完成"?

你可以做的是在这里使用 jQuery 的延迟。 使用承诺,然后在全部完成后调用回调。

未经测试,但您可以执行以下操作:

$.ajax({
    type: "GET",
    url: 'url to json data',
    dataType: "json",
    success: function(data) {
        var time = 10,
            timeouts = [];
        $.each(data, function(key, val) {
            var def = new $.Deferred;
            timeouts.push(def);
            setTimeout(function() {
               console.log(val.term);
               def.resolve();
            }, time);
            time += 10;
        });
        $.when.apply($, timeouts).done(function(){
            alert('finished');
        });
    },
    error: function () {}
})

您也可以将警报放在 setTimeout 中,但在每次迭代时重置它,以便它仅在each成功完成时运行。

$.ajax({
        type: "GET",
        url: 'url to json data',
        dataType: "json",
        success: function(data) {
        var time = 10;
        var t=setTimeout(function(){alert('finished');} , 20);
            $.each(data, function(key, val) {
            setTimeout(function() {
            //document.write(val.term);
              clearTimeout(t);
              t=setTimeout(function(){alert('finished');} , 20);
               return;
            }, time); time += 10;
            });
        },
        error: function () {}
    })