Search code examples
jquerysettimeoutgetjson

JQuery GetJSON inside SetTimeOut Timer


Can anyone post a sample code wherein theres a running timer(javascript settimeout) and doing data retrieval..

basically what i this timer does is to display new messages..

myFunction(param){

//data retrieval operation
//using getJSON.. call displaydata() base on param

settimeout("myFunction()", param, 1000);

}

function displaydata(param){

//processing
alert('test')}

Should i use getJSON? i think theres a problem with the asynchronous call..


Solution

  • Two things I noticed you need to fix in your code.

    • The setTimeout() method has some incorrect arguments
    • Your asynchronous getJSON call creates a race condition between the next timeout and the result of the getJSON method. Do this instead:

    .

    function yourFunction(params) {  
        jQuery.getJSON("url", {data}, function(data, textStatus){
            // handle your JSON results
    
            // Call the timeout at the end of the AJAX response
            // This prevents your race condition
            setTimeout(function(){
                yourFunction(params);
            }, 1000);
        }
    } 
    
    setTimeout(function(){
        yourFunction(params);
    }, 1000);