gpt4 book ai didi

javascript - 在clearTimeout(timer)之后重新启动定时器

转载 作者:行者123 更新时间:2023-12-03 03:27:22 26 4
gpt4 key购买 nike

如何在clearTimeout(timer)之后重新启动另一个函数?

我让refreshTable() 函数在不活动7 秒后停止(没有mousemove 事件)。客户端闲置后移动鼠标是否可以重新开始刷新?

如果可能的话,我想保留顶部函数refreshTable()。

Codepen demo

//====DONT EDIT THIS FUNCTION IF POSSIBLE====
function refreshTable() {
window.clearTimeout(timer);
timer = window.setTimeout(refreshTable, 5000);
$("body").append("<p>refreshTable every 5 seconds.</p>");
}
//========

var timer = window.setTimeout(refreshTable, 0);




// If theres no activity for 7 seconds do something
var activityTimeout = setTimeout(clientInActive, 7000);

function clientResetActive(){
$("body").attr('class', 'active');
clearTimeout(activityTimeout);
activityTimeout = setTimeout(clientInActive, 5000);
//RESTART TIMER WHILE resetActive
//????????
}

// No activity do something.
function clientInActive(){
$("body").attr('class', 'clientInactive');
$("body").append("<p>clientInActive</p>");
//STOP TIMER WHILE clientInActive
clearTimeout(timer);
}

// Check for mousemove, could add other events here such as checking for key presses ect.
$(document).bind('mousemove', function(){clientResetActive()});

像下图这样的东西就是目标。

enter image description here

最佳答案

我建议您有一个函数负责启动超时,另一个函数负责停止超时。试试这个:

//====DONT EDIT THIS TOP FUNCTION IF POSSIBLE====
function refreshTable() {
stopRefreshTable();
window.refreshTableTimer = window.setTimeout(refreshTable, 5000);
$("body").append("<p>refreshTable every 5 seconds.</p>");
}
//====END====

function startRefreshTable() {
if(!window.refreshTableTimer) {
window.refreshTableTimer = window.setTimeout(refreshTable, 0);
}
}

function stopRefreshTable() {
if(window.refreshTableTimer) {
self.clearTimeout(window.refreshTableTimer);
}
window.refreshTableTimer = null;
}

function resetActive(){
$("body").attr('class', 'active');
clearTimeout(activityTimeout);
activityTimeout = setTimeout(inActive, 5000);
//RESTART TIMER WHILE resetActive
startRefreshTable()
}

// No activity do something.
function inActive(){
$("body").attr('class', 'inactive');
$("body").append("<p>inActive</p>");
//STOP TIMER WHILE inActive
stopRefreshTable();
}

// If theres no activity for 7 seconds do something
var activityTimeout = setTimeout(inActive, 7000);
// Check for mousemove, could add other events here such as checking for key presses ect.
$(document).bind('mousemove', function(){resetActive()});
startRefreshTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 在clearTimeout(timer)之后重新启动定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46261186/

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