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 setInterval is a badnews for my application which is why I switch to setTimeout.. But I cant seem to figure out how to make the setTimeout work again after its done loading.. here is what I have tried so far and still trying to make it work at the moment..
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);
Any tips or suggestion ?
Advertisement
Answer
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 }());