建议:把时间设置的小一些,在不同的地方打log,观察是否会重复执行,以及下面本人注释提醒的换成自己的判断条件要修改成自己的,依据自己的需求该进,否则会造成卡死等现象,本人已亲自踩坑
hasOperate(function () {
//执行内容
}, 300000)
function hasOperate(callback, time) {
let timeStatus = true; //控制传进来的函数执行(false:执行)
let settimeStatus = true; //控制定时器setTime关闭(false:关闭)
let timmerr
//监听鼠标或手指按下和弹起
document.body.onmousedown = function () {
// 鼠标或手指按下重新赋值
timeStatus = true;
settimeStatus = true
}
document.body.onmouseup = function () {
// 先关闭之前的timmerr定时器,在执行之后的
clearTimeout(timmerr)
timmerr = setTimeout(() => {
countTime();
}, 1000)
}
// 把变量放到外面,就可以删除上一次的定时
let setTime
let timer;
function countTime() {
// 先关闭setTime和timer两个定时器,避免重复执行
clearInterval(setTime);
clearTimeout(timer);
setTime = setInterval(function () {
if (!timeStatus) {
callback();
timeStatus = true;
// 执行完函数关闭本身的定时器,避免造成内存泄漏
clearInterval(setTime);
}
if (!settimeStatus) {
// 当在锁屏页面点击时,进入到这里来关闭定时器
clearInterval(setTime);
}
}, 1000); // 这里我是以秒为单位监听的,自己也可以改自己的
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
// 根据锁屏的状态给赋值(自己可以换成别的判断条件)
if (document.getElementById('lock_screen').style.display == 'block') {
timeStatus = true;
// 让上面setTime定时器关闭
settimeStatus = false
} else if (document.getElementById('lock_screen').style.display == 'none') {
timeStatus = false;
}
}, time);
}
countTime();
}