简体   繁体   English

在jQuery Mobile中每3秒执行一次功能

[英]Execute a function every 3 seconds in jquery mobile

Am trying to create a function in jquery mobile that autorefreshes itself every 3 seconds when on a certain page. 我正在尝试在jquery mobile中创建一个函数,该函数在特定页面上每3秒自动刷新一次。

I have tried: 我努力了:

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

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

 });

How can i change the function to console.log('its after 3 sec') after 3 seconds that is how can i add the time interval.The function should only execute when one is on the page(#chat) 我如何在3秒后将函数更改为console.log('3秒后'),这就是我如何添加时间间隔的功能。仅当页面上有一个函数时才执行该函数(#chat)

You can use the setInterval method, it will execute the specified function at the desired interval ( in milliseconds ). 您可以使用setInterval方法,它将以所需的时间间隔( 以毫秒为单位 )执行指定的函数。

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

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

    setInterval(autoload(), 3000);

});

To stop execution when hiding the page, you could store the interval id and use the clearInterval method. 要在隐藏页面时停止执行,可以存储间隔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);
});

You can also use the setTimeout method, similar to the setInterval method. 您也可以使用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);
});
$(document).on('pageshow', '#chat',function(){
    function autoload(){
        console.log('its after 3 sec')
    } 
    window.setInterval(autoload, 3 * 1000)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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