views:

128

answers:

2
function load_result()
{
    $.getJSON( "http://somesite.com/loadresult.php", function(data) {
        if( data == undefined || data == null )
        {
            console.log( "no data" );
            clearTimeout( lr_timeout );
            lr_timeout = setTimeout( "load_result()", 2000 );
            return;
        }
        insert_result_price( data );
        clearTimeout( lr_timeout );
        lr_timeout = setTimeout( "load_result()", 50 * ( Math.random() * 10 ) );

    } );
}

and lr_timeout is defined globally and the load_result function is kicked off initially in the document.ready function. The problem is that the function doesn't always run. I'll watch it in Firebug and I have another function that's set on a setInterval that always works.

Ideas?

A: 

I have never experienced a problem with setTimeout generally, and I've used it for a main/infinite loop in JS quite a few times without it ever having an issue. I would imagine that clearTimeout from one invocation of load_results is stepping on setTimeout from another, especially since it's in response to a GET request that may take longer than it takes the browser to get around to the next setTimeout. There actually are multiple threads going on here, you just have no control over them and there is no synchronization mechanism available.

flatline
Well.. wouldn't it wait for the response from the GET since it's in the callback?
Shamoon
That's true, they really should go sequentially. I guess my only suggestion is, get rid of clearTimeout and see if it makes a difference.
flatline
+1  A: 

Is your other setTimeout function (the one that always works) also inside a $.getJSON? If so, does it call it on the same URL (http://somesite.com/loadresult.php in your example, but I'm sure it's different in real life)?

It's possible that http://somesite.com/loadresult.php is a flaky resource, and your inconsistent results are due to that resource, not setTimeout. Of course, if they're both using that same resource, then that couldn't be the problem.

jboxer
That's a setInterval actually, and it's not related to the loadresult resource.
Shamoon
But like jboxer said, did you check if it's a flaky source? The setTimeout in your code never gets called if data is null or undefined.
Annie