簡體   English   中英

我有由setInterval每3分鍾調用一次的JS函數-當頁面也加載時如何調用它?

[英]I have the JS function that is invoked every 3 minutes by setInterval - how can I invoke it when page loads too?

我有以下腳本:

    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

並從頁面list.php獲取JSON字符串,並在#device-content-user-text div中一一打印結果。 每五分鍾完成一次,當用戶加載頁面時,計時器開始計時。 我如何在頁面加載時(通常每5分鍾一次)調用此函數? 謝謝

使用document.ready()之類的

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

另外,如果您只是在setInterval的匿名函數內調用myFunction,則只需傳遞函數引用本身即可

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

更新資料

根據頁面“加載”的含義, document.readyload()之間可能會有很大的不同。 如果您想絕對確定是否已加載所有內容(包括幀,圖像等),請執行

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

否則,如果DOM准備就緒就足夠了,那就堅持document.ready()

請參閱jQuery-$(document).ready和$(window).load有什么區別?

 //Document ready
   $(function(){

        //call function
        myFunction();

       //put your interval here

    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM