1

I have the following script:

    var results;
var cursor = 0;

function myFunction () {
    $.getJSON('list.php', function(json) {
        results = json.result;
        cursor = 0;

        // Now start printing
        printNext();
    });
}

function printNext(){
    if(cursor == results.length){
        // Reset the cursor back to the beginning.
        cursor = 0;
    }

    // Print the key1 in the div.
    //$('#device-content-user-text').html(results[cursor].key1);
    $('#device-content-user-text').hide('fast', function(){ $('#device-content-user-text').html(results[cursor].key1); $('#device-content-user-text').show('fast'); });

    // Set a delay for the current item to stay
    // Delay is key2 * 1000 seconds
    setTimeout(function(){
        printNext();
    }, results[cursor].key2 * 1000);

    // Advance the cursor.
    cursor++;
}

var interval = setInterval(function () { 
    myFunction(); 
}, 300000);  //make sql query every 5 minutes

and it gets the JSON string from the page list.php and prints the results one by one in a #device-content-user-text div. It is done every five minutes and the timer starts counting time when the user loads the page. How can I invoke this function also on the page load (and then normally every 5 minutes)? Thanks

randomuser1
  • 2,733
  • 6
  • 32
  • 68

2 Answers2

4

Use document.ready() like

$(document).ready(function(){
    var interval = setInterval(function () { 
        myFunction(); 
    }, 300000);  //make sql query every 5 minutes
    myFunction();
});

Also, if your just calling myFunction inside the anonymous function of setInterval, just pass the function reference itself

$(document).ready(function() {
        var interval = setInterval(myFunction, 300000); //make sql query every 5 minutes
        myFunction();
    });

Update

Depending on what you meant by page 'load', there can be a world of difference between document.ready and load(). If you want to be absolutely sure everything is loaded(including frames, images, etc..) then do

$(window).load(function() {
            var interval = setInterval(myFunction, 300000); 
            myFunction();
        });

Otherwise, if it is sufficient that the DOM is ready, just stick with document.ready()

See jQuery - What are differences between $(document).ready and $(window).load?

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
0
 //Document ready
   $(function(){

        //call function
        myFunction();

       //put your interval here

    });
dansasu11
  • 875
  • 1
  • 9
  • 17