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

Execute a function every 3 seconds in jquery mobile

本文关键字:一次 函数 执行 mobile jquery 中每      更新时间:2023-09-26

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

我试过:

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

如何在 3 秒后将函数更改为控制台.log("3 秒后"),这就是我如何添加时间间隔。该函数应仅在页面上执行(#chat)

您可以使用 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);
});
$(document).on('pageshow', '#chat',function(){
    function autoload(){
        console.log('its after 3 sec')
    } 
    window.setInterval(autoload, 3 * 1000)
});