Run A Javascript Function Continuously Repeating With A Time Interval
Solution 1:
This will repeat the task until you clear the interval (with clearTimeout(repater))
var repeater;
functiondoWork() {
$('#more').load('exp1.php');
repeater = setTimeout(doWork, 1000);
}
doWork();
Per OP's original condition:
I want code that repeat function continuously...
Solution 2:
you can do this like
var myFunction = function() {
$('#more').load('bla.php');
};
var timer = setInterval(myFunction, 1000); // call every 1000 milliseconds
or
var timer = setTimeout(myFunction, 1000); // call every 1000 millisecondsclearTimeout(timer); //To stop the function from being called forever
as @Christofer Eliasson For an Ajax-request, you would probably want to use a timeout instead of an interval, an start the timeout again in the callback, to make sure that you don't stack calls if the server is taking more than 1 second to respond
Good Read
Solution 3:
For an Ajax-request I would use a timeout instead of an interval, and start the timeout again in the callback of the ajax-request.
If you use an interval of say 1 second and your server takes more than one second to respond, you will start to stack calls with an interval, since the interval will call the function every second no matter what. With the timeout-in-callback approach instead, you wouldn't start the countdown until previous request has completed.
I'm using an IIFE to trigger the first call to the function. Then when the load has completed, I use a timeout to call the function again after one second:
(functionloadContent(){
$('#more').load('exp1.php', function () {
setTimeout(loadContent, 1000);
});
})();
Solution 4:
Just throwing it out there:
functiondoRequest() {
$.ajax({
url: 'exp1.php',
timeout: 1000,
success: function(data) {
$('#more').html(data);
doRequest();
}
});
}
Solution 5:
How about some good ol' fashion recursion?
function getStuff() {
$('#more').load('exp1.php', function() {
getStuff();
});
}
getStuff();
Post a Comment for "Run A Javascript Function Continuously Repeating With A Time Interval"