首页 > 解决方案 > 如何在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(); 

标签: javascriptrecursionknockout.jssettimeout

解决方案


这是我的解决方案。请检查。

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);


推荐阅读