简体   繁体   中英

Execute a function every 30 seconds jquery mobile?

I have a jquery mobile phonegap application. I would like to execute a function every 30 seconds the user stays on a particular page.

If the user stays on a particular page say page1 , i would like to execute a function every 30 seconds,

To put it in simpler words

If active page is page1 fire getmessages() every 30 seconds.

How do i achieve this

USE settimeinterval

Check this DEMO

<div id="div2>
<input type="text" name="divText" value="q3"/>
</div>

setInterval(function() {
 alert('HI')
}, 30000);

Time is in ms (1000= 1 sec)

You can setInterval .

Code:

$(document).ready(function(){
function myFunction()
{
setInterval(function(){alert("Hello")},3000);
}

$('#click').click(function(){

myFunction()

})

})

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.

Demo link 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 .

Retrieve page's id on those events then use switch / case to execute functions as well as clearInterval when page is hidden.

/* 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;
    }
}

Demo

Working Fiddle

Reference Link

setInterval(function() {
  // Do something every 30 seconds
}, 30000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM