Jquery/ajax循环设置超时

Jquery/ajax Looping SetTimeout

本文关键字:设置 超时 循环 ajax Jquery      更新时间:2023-09-26

嗨,我的setTimeout函数被卡住了。我想做的是为我的检索会话函数循环我的setTimeout。。我在setInterval上尝试过,但使用setInterval对我的应用程序来说是个坏消息,这就是我切换到setTimeout的原因。。但是我似乎不知道如何让setTimeout在加载完成后再次工作。。以下是我迄今为止所做的尝试,目前仍在努力使其发挥作用。。

Javascript:

id = setTimeout(function()
{
    $.ajax(
    {
        url: "includes/handlechat.php",
        type: "GET",
        data: data,
        dataType: 'json',
        success: function(result)
        {
            $("#clog").empty();
            $.each(result, function(rowKey, row) 
            {
                $("#clog")
                    .append('<p ><h4>'+ row.username +':</h4>' + row.message_content + '</p>' );
            });
        },
        complete: function () 
        { 
            clearTimeout(id);
        }
    })
}, 1101);

有什么建议吗?

将代码放入函数中,并在成功或完成处理程序中调用它:

function load() {
    setTimeout(function () {
        $.ajax({
            url: "includes/handlechat.php",
            type: "GET",
            data: data,
            dataType: 'json',  
            success: function (result) {
                $("#clog").empty();
                $.each(result, function (rowKey, row) {
                    $("#clog").append('<p ><h4>' + row.username + ':</h4>' + row.message_content + '</p>'); 
                }); 
            },
            complete: load
        });
    }, 1101);
}
load();

您还可以使用IIFE来避免在当前环境中创建另一个绑定:

(function load() {
   // setTimeout here
}());

我会做这样的事情。

function getChatMessages() {
    $.ajax({
        // your params here
    }).done(function (data) {
        // do something with the data
    }).always(function () {
        window.setTimeout(getChatMessages, 1101);
    });
}
getChatMessages();

".总是"的目的是为了避免在获取消息时出现一些错误(超时、某种500等),从而中断循环。

$.ajax({
 url: "includes/handlechat.php",
        type: "GET",
        data: data,
        dataType: 'json', 
            success:function(data){
 //your succesfull code
            },
            error:function(){
            //code when time is out
            },
            timeout:10000  // will return the code in error after 10 seconds
        });