Jquery/ajax Looping SetTimeout

后端 未结 2 923
孤独总比滥情好
孤独总比滥情好 2021-01-03 16:58

Hi I\'m stuck on my setTimeout function. What i\'m trying to do is to loop my setTimeout for my retrieve conversation function.. I have tried this on setInterval but using s

相关标签:
2条回答
  • 2021-01-03 17:30

    Put the code in a function and call it in the success or complete handler:

    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();
    

    You can also use an IIFE to avoid creating another binding in the current environment:

    (function load() {
       // setTimeout here
    }());
    
    0 讨论(0)
  • 2021-01-03 17:33

    I'd do something like this.

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

    Purpose of the '.always' is so you don't get some error on fetching messages (timeout, some kind of 500, etc) that breaks your loop.

    0 讨论(0)
提交回复
热议问题