小白遇到了 setTimeout 停止的问题

let s, n = 0;

function mainLoop() {

s = setTimeout(function () {

    doSomeThing();

    mainLoop();}, 1000);

}

function doSomeThing() {

n ++;

console.log(n);if (n > 5) {    stop();
}

}

function stop() {

console.log("---stop----")

clearTimeout(s);

}

mainLoop();

上面这段代码为什么执行五次以后不会自动停止啊?


缥缈止盈
浏览 1439回答 2
2回答

慕工程0101907

稍微改了一下调用顺序,mainLoop();出现了死循环,你判断之后计时器虽然停了,但方法调用时又重新启动了mainLoop()里的计时器 let s, n = 0;        function mainLoop() {             s = setTimeout(function () {                 doSomeThing();                             }, 1000);         }        function doSomeThing() {             n++;            console.log(n);            if (n > 4) {                 stop();             }else{                 mainLoop();             }         }        function stop() {            console.log("---stop----")             clearTimeout(s);         }         mainLoop();

德玛西亚99

把这个doSomeThing();拿出来就行,function mainLoop() {             s = setTimeout(function () {                 mainLoop();             }, 1000);             doSomeThing();         }
打开App,查看更多内容
随时随地看视频慕课网APP