gpt4 book ai didi

javascript - 在jquery mobile中每3秒执行一个函数

转载 作者:行者123 更新时间:2023-11-28 18:37:25 25 4
gpt4 key购买 nike

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

我已经尝试过:

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

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

});

如何在 3 秒后将函数更改为 console.log('its after 3 sec') ,这就是如何添加时间间隔。该函数应该仅在页面上时执行(#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);
});

关于javascript - 在jquery mobile中每3秒执行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com