Search code examples
javascriptasynchronouscallbacksettimeoutstack-overflow

How to make infinite calls for a div reload through Ajax synchronously


I'm kind of new to javascript and seriously, this async thing is driving me crazy.

I'm working on a project for displaying a div (which occupies all the screen) that reloads everytime with a different content and stays on screen for an X amount of time.

For example, I already created some static screens objects inside an array like this:

screenArray[0] = {ID:"987234", Name:"SampleScreen", Time:6000};
screenArray[1] = {ID:"837625", Name:"SampleScreen2", Time:10000};   

So this is pretty much what I wanted to do if javascript worked synchronously:

function ScreenEngine(){
    reloadScreenContent();// "loads" the first screen (this is just an Ajax div reload function)
    for (var i = 0; i == screenArray.length+1; i++){
        if (i == screenArray.length){ //when it gets to the latest screen, it goes to the first one
            i = 0;
        }
        setTimeout(reloadScreenContent, screenArray[i].Time); // loads the second screen with the timeout of the first one (i=0)
    }
}

(I'm just working on the timey wimey thingy, I'll deal with the content later.)

Saw some other posts about callback functions so javascript would work "synchronously" for the things I want and I even tried some of it and failed miserably doing it.

Even not understanding with details how I would make a callback function, I understand that (at least the way I "tried") it would stack forever because I'm asking javascript to do an infinite job.

I need a brainstorm how to solve this problem, maybe some tips using callback or a similar sample code so I can guide myself.


Solution

  • I think what you need to do is call the reload function inside the callback function itself. If you're using jQuery for the ajax function, the code could look something like this:

    function loadContent(){
        $.getJSON("yourURL", callback)
    }
    
    function callback(data){
        /*do something with the data*/
        /*call loadContent at an interval */
        window.setTimeout(loadContent, 2000 );
    }
    
    loadContent(); 
    

    This was loadContent will get called 2s after the content has been loaded. Here's an example of a recursive ajax call, you can see in the console it's making the ajax call every 10s http://jsfiddle.net/w66peL7b/1/