Javascript 电子束中的定时函数
我不熟悉java脚本和电子。我正在尝试编写一个有开始按钮和停止按钮的应用程序。单击开始按钮时,应该启动一个计时器,该计时器每隔一段时间执行一个函数,直到单击停止按钮为止。在互联网上翻了一番之后,我发现SetInterval()函数应该可以做到这一点。这是我的代码:Javascript 电子束中的定时函数,javascript,timer,electron,setinterval,Javascript,Timer,Electron,Setinterval,我不熟悉java脚本和电子。我正在尝试编写一个有开始按钮和停止按钮的应用程序。单击开始按钮时,应该启动一个计时器,该计时器每隔一段时间执行一个函数,直到单击停止按钮为止。在互联网上翻了一番之后,我发现SetInterval()函数应该可以做到这一点。这是我的代码: let timeoutObj; const startTimer = () => { let val = document.getElementById("time-input").value;
let timeoutObj;
const startTimer = () => {
let val = document.getElementById("time-input").value;
document.getElementById("time-input").disabled = true;
document.getElementById("start-btn").disabled = true;
document.getElementById("stop-btn").disabled = false;
timeoutObj = setInterval(execution(), val * 10);
}
const stopTimer = () => {
let val = document.getElementById("time-input").value;
document.getElementById("time-input").disabled = false;
document.getElementById("start-btn").disabled = false;
document.getElementById("stop-btn").disabled = true;
stopExecution();
}
const execution = () => {
console.log('exetuted');
}
const stopExecution = () => {
console.log('stopping');
clearInterval(timeoutObj);
}
它不工作,只记录“启动”一次,再也不会这样做。startTimer()和stopTimer()是按钮的onclick函数。有人能解释一下为什么它不起作用吗?
顺便说一句:该值非常低,它应该每3秒记录一次“启动”。javascripts setInterval函数期望函数回调作为参数,但是您传递了
execution()
有效地执行函数并传递其返回值,而不是回调
你应该这样做
setInterval(execution, val*10) // pass execution callback, instead of calling it
尝试setInterval(execution)
,而不是setInterval(execution())
。