javascript - 如何在javascript中杀死并重新启动递归函数
问题描述
我正在研究淘汰赛js。因为我有一个递归函数,它每分钟执行一个函数。因为我每 60 秒使用一次计时器,它也会执行,同样也会反映在 UI 中。在我的情况下,如果我尝试分配或初始化一个循环内的计时器值(可观察),它不会反映而不是反映它被添加到管道中,并且同时运行了很多时间循环。在这种情况下,我想终止循环,并在每次更改计时器值时再次重新启动。
定时器InSec=60;
var loop = function () {
if (this.timer() < 1) {
myFunction()
this.timer(this.timerInSec - 1);
setTimeout(loop, 1000);
} else {
this.timer(this.timer() - 1);
setTimeout(loop, 1000);
}
};
loop();
解决方案
这是我的解决方案。请检查。
timerInSec = 60;
const Loop = (function () {
let timer = 0;
let timerId = -1;
const myFunction = function () {
console.log('finished');
}
const fnLog = function (tm) {
console.log('current time = ', tm);
}
const fnProc = function () {
timerId = setTimeout(myFunction, 1000 * timer);
}
return {
start: function (tm = 60) {
this.stop();
timer = tm;
fnProc();
},
stop: function () {
if (timerId !== -1) {
clearTimeout(timerId);
timerId = -1;
}
}
}
})();
Loop.start(timerInSec);
setTimeout(() => {
Loop.start(timerInSec);
}, 500);
推荐阅读
- c# - 将带有 css 的 div 保存为 pdf 文件 ASP.net C#
- python - 选择包含特定整数的所有数据框行
- python - Python:使用可选标志创建正则表达式函数
- r - 如何获得 R 安装日期?
- node.js - 使用 cPanel 的 NodeJs 中的环境变量
- lucene - Lucene (8.5.0) - 如何使用通配符突出显示已解析的查询?
- c# - 显示数据库中的图片
- spring-boot - 使用 Spring Boot liquibase 测试不适用于多个数据源
- reactjs - 将数据推送到 Firebase 的问题
- laravel - laravel 验证检查多维数组