2

I want to continuously update an html document using the return of a php file. Therefore I need to use the jQuery function:

$.get('returnfunction.php', function(data) { 
test=data;
document.getElementById('t1').innerHTML=test; 
}); 

How can I call this function continuously in javascript? setInterval seems not proper for this asynchronous function.

Thanks

2
  • in setInterval, the "data" variable is not updated.If you know a solution that works please let me know, it doesnt need to be very efficient or something. The update should be between 1-5 seconds Commented Sep 4, 2013 at 15:42
  • The Javascript timers are not accurate because they are designed to yeild to other events that are going on in the page. Commented Sep 4, 2013 at 15:43

2 Answers 2

3

The problem with calling an asynchronous function using setInterval is that the unanswered requests might accumulate if the server or the network is slow.

Here's how you might do it :

(function doOne(){
    $.get('returnfunction.php', function(data) { 
       test=data; 
       document.getElementById('t1').innerHTML=test;
       setTimeout(doOne, 1000);
    }); 
})();

This way the next call to $.get occurs one second after the server has answered the last call.

You might also want to act on failures, not just on success, depending on your exact requirements.

Sign up to request clarification or add additional context in comments.

Comments

2

setInterval probably isn't a good idea since the order is not guaranteed, therefore you could be sending requests every X amount of seconds that either come back all at once, not at all, or in a random order. You can use setTimeout in the callback to start another request in X amount of time:

function getStuff() {
    $.get('returnfunction.php', function(data) { 
        test=data;
        document.getElementById('t1').innerHTML=test; 
        setTimeout(getStuff, 5000); //Run this func again in 5 sec
    }); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.