[英]Execute a function every 30 seconds jquery mobile?
I have a jquery mobile phonegap application. 我有一个jquery手机差距应用程序。 I would like to execute a function every 30 seconds the user stays on a particular page.
我想每30秒执行一次用户停留在特定页面上的功能。
If the user stays on a particular page say page1 , i would like to execute a function every 30 seconds, 如果用户停留在特定页面上说第1页,我想每隔30秒执行一次功能,
To put it in simpler words 用简单的话说
If active page is page1 fire getmessages() every 30 seconds. 如果活动页面是page1 fire getmessages(),每30秒。
How do i achieve this 我如何实现这一目标
You can setInterval
. 你可以
setInterval
。
Code: 码:
$(document).ready(function(){
function myFunction()
{
setInterval(function(){alert("Hello")},3000);
}
$('#click').click(function(){
myFunction()
})
})
HTML: HTML:
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<p>After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on forever...</p>
<button id="click">Try it</button>
Replace 3000(3 sec) --> 30000 (30 sec)
for your requirement. 根据您的要求更换
3000(3 sec) --> 30000 (30 sec)
。
Demo link http://jsfiddle.net/dhana36/2c4ps/ 演示链接http://jsfiddle.net/dhana36/2c4ps/
If you're using jQuery Mobile 1.4, you need to listen to pagecontainershow
and pagecontainerhide
events in order to execute functions with interval based on page id
. 如果您正在使用jQuery Mobile 1.4,则需要监听
pagecontainershow
和pagecontainerhide
事件,以便根据页面id
执行间隔 。
Retrieve page's id
on those events then use switch / case to execute functions as well as clearInterval
when page is hidden. 检索这些事件上的页面
id
,然后使用switch / case执行函数以及隐藏页面时的clearInterval
。
/* setInterval function's name */
var interval;
/* 1) On page show, retrieve page's ID and run checkPage()
2) On page hide, clearInterval() */
$(document).on("pagecontainershow", function () {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage")[0].id;
checkPage(activePage);
}).on("pagecontainerhide", function () {
clearInterval(interval);
});
/* Run function(s) based on page's ID */
function checkPage(page) {
switch (page) {
case "p1":
interval = setInterval(function () {
/* function(s) */
}, 30000);
break;
case "p2":
interval = setInterval(function () {
/* function(s) */
}, 30000);
break;
}
}
setInterval(function() {
// Do something every 30 seconds
}, 30000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.