[英]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(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.ready
和load()之間可能會有很大的不同。 如果您想絕對確定是否已加載所有內容(包括幀,圖像等),請執行
$(window).load(function() {
var interval = setInterval(myFunction, 300000);
myFunction();
});
否則,如果DOM
准備就緒就足夠了,那就堅持document.ready()
//Document ready
$(function(){
//call function
myFunction();
//put your interval here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.