Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a JavaScript function continuously repeating with a time interval

This is my first question, and I would appreciate you answering soon.

I would like code to repeat a function continuously... I have tried some code but it hasn't worked.

I tried this code:

<script type="text/javascript">
$(function() 
{
$('#more').load('exp1.php'); // SERIOUSLY!
});
</script>

I want to repeat this function after some interval. I have tried setInterval() and setTimeout()

But, I haven't received results.

like image 882
Sarvesh Godbole Avatar asked Dec 15 '12 18:12

Sarvesh Godbole


2 Answers

This will repeat the task until you clear the interval (with clearTimeout(repater))

var repeater;

function doWork() {
 $('#more').load('exp1.php');
 repeater = setTimeout(doWork, 1000);
}

doWork();

Per OP's original condition:

I want code that repeat function continuously...

like image 182
hyankov Avatar answered Oct 17 '22 07:10

hyankov


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 milliseconds

clearTimeout(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

  1. MDN:window.setTimeout
  2. MDN:window.setInterval
like image 41
NullPoiиteя Avatar answered Oct 17 '22 09:10

NullPoiиteя