What is an alternative to setInterval in jQuery?
<p>I am using jQuery to call a function when a button is clicked. This function that is being called is in PHP and returns logging information. I have tried to use <code>setInterval()</code> but it calls the function at whatever rate I choose and tends to return duplicate logging information and most of the time it freezes. Is there a way that I can make repeated calls to a PHP function from jQuery, but only call the function after the last call is finished and returned?</p>

<p>Here is the jQuery code that makes involves the <code>setInterval()</code></p>

<pre><code>setInterval(
            function(){
                $.getJSON("ajax.php?function=tail&amp;pointer=" + ftell,
                    function(data){
                        var obj = [];
                        obj = $.parseJSON(data); 

                        ftell = obj[0];
                        $("#tail").append(obj[1]);
                    });
            }, 2000);
</code></pre>

<p>Here is the PHP function that it calls</p>

<pre><code>function tail(){
    $file = "/path/to/the/log/file.log";
    $handle = fopen($file, "r");
    clearstatcache();

    $currentSize = filesize($file);            
    $offset = $_REQUEST['pointer'] - $currentSize;

    if ($_REQUEST['pointer'] == 0) {
        fseek($handle, -1024, SEEK_END);
    } else {
        fseek($handle, $_REQUEST['pointer'], SEEK_END);
    }

    while ($buffer = fgets($handle)) { 
        $log .= $buffer . "&lt;br /&gt;";
    } 

    fclose($handle);      
    $results = array('0' =&gt; $currentSize, '1' =&gt; str_replace('"', '\"', $log));     
    echo json_encode($results);
}
</code></pre>
