2016-04-24 88 views
0

我試圖在jquery mobile中創建一個函數,該函數在特定頁面上每3秒自動刷新一次。在jquery mobile中每3秒執行一次函數

我曾嘗試:

$(document).on('pageshow', '#chat',function(){ 

function autoload(){ 
    console.log('its after 3 sec') 
    } 
autoload(); 

}); 

我怎樣才能改變功能CONSOLE.LOG(「其3秒後」)3秒鐘後,這是我怎樣才能添加的時間只有interval.The函數應該當執行一個是在頁面(#chat)

+0

'window.setInterval()'? – Redu

+0

http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript的副本? –

回答

2

可以使用setInterval方法,它將在(以毫秒爲單位)所需的時間間隔執行指定的功能。

$(document).on('pageshow', '#chat', function() { 

    function autoload() { 
     console.log('its after 3 sec') 
    } 

    setInterval(autoload(), 3000); 

}); 

要隱藏頁面時停止執行,你可以存儲間隔ID,並使用clearInterval方法。

// store the interval id so we can clear it when the page is hidden 
var intervalId; 

$(document).on('pageshow', '#chat', function() { 
    function autoload() { 
     console.log('its after 3 sec') 
    } 
    intervalId = setInterval(autoload(), 3000); 
}); 

$(document).on('pagehide', function() { 
    clearInterval(intervalId); 
}); 

您還可以使用setTimeout方法,類似於setInterval方法。

// store the timeout id so we can clear it when the page is hidden 
var timeoutId; 

$(document).on('pageshow', '#chat', function() { 
    function autoload() { 
     console.log('its after 3 sec') 
     timeoutId = setTimeout(autoload(), 3000); 
    } 
    autoload(); 
}); 

$(document).on('pagehide', function() { 
    clearTimeout(timeoutId); 
}); 
+0

感謝它的工作,但我如何停止頁面隱藏功能,因爲即使當我離開頁面時功能仍然繼續 –

+0

另一種做法是使用間隔ID。這將允許您管理多個間隔。請參閱http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript –

1
$(document).on('pageshow', '#chat',function(){ 
    function autoload(){ 
     console.log('its after 3 sec') 
    } 
    window.setInterval(autoload, 3 * 1000) 
}); 
+0

它可以在頁面隱藏 –

+0

@GEOFFREYMWANGI上工作,你需要使用'var myInterval = window.setInterval(...)'跟蹤計時器,然後你可以用'window.onblur = function永久停止它(){clearInterval(myInterval)}' – Plato