在jquery mobile中每3秒执行一次函数

时间:2016-04-24 23:46:28

标签: javascript jquery jquery-mobile

尝试在jquery mobile中创建一个函数,在某个页面上每3秒自动刷新一次。

我试过了:

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

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

 });

如何在3秒后将功能更改为console.log('3秒后'),即如何添加时间间隔。该功能只应在页面上执行时才会执行(#chat)< / p>

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:1)

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