我正在尝试编写一个计时器函数。在第一个状态下,计时器可以工作,但它执行的代码必须分别放置在计时器内的 goActive/goInactive
函数内。现在,我尝试通过让 goActive/goInactive 返回小信号变量(其他代码块可以解释这些变量)来将计时器与函数调用分开。
现在我只有一个简单的模型。我希望 goActive
和 goInactive
返回 1 或 -1,然后另一个函数 checktimer
应该在更新时将它们写入屏幕。但我还没弄清楚其中的逻辑。我对 JS 很陌生;我感谢所有帮助:
var TimeoutID;
var timerstatus = 0;
function inputdetect() {
// attaches event handler to specified event
// takes event as string, function to run, and optional boolean
// to indicate when the event propogates
// these are false, so events "bubble up"
this.addEventListener("mousemove", resetTimer, false);
this.addEventListener("mousedown", resetTimer, false);
this.addEventListener("mousewheel", resetTimer, false);
this.addEventListener("keypress", resetTimer, false);
this.addEventListener("touchmove", resetTimer, false);
this.addEventListener("DOMmousescroll", resetTimer, false);
this.addEventListener("MSpointermove", resetTimer, false);
startTimer();
}
inputdetect();
function startTimer() {
//waits two seconds before calling inactive
TimeoutID = window.setTimeout(goInactive, 2000); // does it need to take the window variable??
}
function resetTimer(e) {
window.clearTimeout(TimeoutID);
goActive();
}
function goActive() {
//what happens when the UI is not idle
$('#hi').text("The UI is not idle.");
timerstatus = 1;
$('#var').text(timerstatus);
startTimer();
return timerstatus;
}
function goInactive() {
$('#hi').text("The UI is idle.");
timerstatus = -1;
$('#var').text(timerstatus);
return timerstatus;
// REPLACING CURSOR WHEN UI IS IDLE
//this part won't work
}
function checktimer(timerstatus) {
$('#ct').text(timerstatus);
}
$(document).ready(function() {
window.setInterval(checktimer(timerstatus), 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div>check timer update goes: <span id="ct"></p></div>
<!--this is where the HTML will go*/-->
<p id = "hi">hello</p>
<p id = "ts">Timer status is: <span id = "var"></span>
</p>
最佳答案
这是不正确的。
window.setInterval(checktimer(timerstatus), 2000);
您需要传递一个函数而不是调用一个函数。
因为timerstatus
是一个全局变量,它已经被所有函数共享,所以你不需要传递和返回它。所有功能都可以直接使用。
因此只需将 checktimer
传递给 setInterval
即可。
window.setInterval(checktimer, 2000);
删除所有 returntimerstatus;
行,并删除 checktimer
的参数:
function checktimer() {
$('#ct').text(timerstatus);
}
我不知道这是否符合您最终想要的,但它确实纠正了代码。
关于javascript - 写函数不读定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31493127/