let doit = (from, to) => {
let a = setTimeout(doit, 500, ++from);
console.table(from);
if (from === to) {
clearTimeout(a)
}
};
doit(6, 13);编写一个printNumbers( from,to)函数,它每秒钟打印一个数字,从开始到结束。你能描述一下为什么这个计时器不停车吗?请你给我答复一下。
发布于 2022-02-22 14:16:02
它不会停止,因为您没有将to传递到递归调用。你只是路过++from。如果同时记录这两个值,这将是相当明显的:
let doit = (from, to) => {
let a = setTimeout(doit, 500, ++from);
console.log(from, to);
if (from === to) {
clearTimeout(a)
}
};
doit(6, 13);
解决方案也是通过to
let doit = (from, to) => {
let a = setTimeout(doit, 500, ++from, to); //
console.log(from, to);
if (from === to) {
clearTimeout(a)
}
};
doit(6, 13);
https://stackoverflow.com/questions/71222529
复制相似问题