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:
JavaScript
x
24
24
1
id = setTimeout(function()
2
{
3
$.ajax(
4
{
5
url: "includes/handlechat.php",
6
type: "GET",
7
data: data,
8
dataType: 'json',
9
success: function(result)
10
{
11
$("#clog").empty();
12
$.each(result, function(rowKey, row)
13
{
14
$("#clog")
15
.append('<p ><h4>'+ row.username +':</h4>' + row.message_content + '</p>' );
16
});
17
},
18
complete: function ()
19
{
20
clearTimeout(id);
21
}
22
})
23
}, 1101);
24
Any tips or suggestion ?
Advertisement
Answer
Put the code in a function and call it in the success or complete handler:
JavaScript
1
19
19
1
function load() {
2
setTimeout(function () {
3
$.ajax({
4
url: "includes/handlechat.php",
5
type: "GET",
6
data: data,
7
dataType: 'json',
8
success: function (result) {
9
$("#clog").empty();
10
$.each(result, function (rowKey, row) {
11
$("#clog").append('<p ><h4>' + row.username + ':</h4>' + row.message_content + '</p>');
12
});
13
},
14
complete: load
15
});
16
}, 1101);
17
}
18
load();
19
You can also use an IIFE to avoid creating another binding in the current environment:
JavaScript
1
4
1
(function load() {
2
// setTimeout here
3
}());
4