最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Execute a function every 30 seconds jquery mobile? - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Jan 31, 2014 at 11:19 vijarvijar 7814 gold badges14 silver badges25 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

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)

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

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/dhana36/2c4ps/

Working Fiddle

Reference Link

setInterval(function() {
  // Do something every 30 seconds
}, 30000);
发布评论

评论列表(0)

  1. 暂无评论