Reputation: 3320
I want to do the following application:
1) I want to retrieve the message using ajax. (Jquery)
2) When I read the message - I want to wait 10 seconds to retrieve the next message
3) Then wait another 10 seconds to retrieve the next message
4) All rows in a database.
How to use the timer in this case?
How can I start and then stop the timer?
function loadMessage(user_id)
{
$.post('ActionScripts/Message.php',{
user_id: user_id
}, function(data) {
//data
},"json");
}
Upvotes: 0
Views: 930
Reputation:
I prefer calling the next ajax request after the completion of the previous (not as important with 10000 interval), but you do have to call the next one even if the first fails...
function loadMessage(user_id) {
$.ajax({
type: "POST",
url: 'ActionScripts/Message.php',
data: { user_id: user_id }
dataType: 'json',
async: true,
cache: false,
timeout:30000,
success: function(data){
// do what you need with the returned data...
setTimeout(function(){loadMessage(user_id); },10000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//do what you want with the error
setTimeout(function(){loadMessage(user_id); },10000);
}
});
}
Upvotes: 1
Reputation: 35399
The following implementation calls off to the server and executes every 10 seconds:
function loadmessage (user_id) {
$.post('ActionScripts/Message.php', {
user_id: user_id
}, function (data) {
//data
}, "json");
}
var interval = setInterval(function() { loadmessage(5345) }, 10000);
To stop the timer use clearInterval
:
clearInterval(interval);
To restart the timer re-initialize
the interval
variable:
var interval = setInterval(function() { loadmessage(5345) }, 10000);
Upvotes: 0
Reputation: 1389
function loadMessage(user_id)
{
$.post('ActionScripts/Message.php',{
user_id: user_id
}, function(data) {
//data
setTimeout(function(){loadMessage(user_id); }, 10000);
},"json");
}
Upvotes: 4