第九条那个,因为你每次递归就建了两次工具函数和清理函数。其实把 print 函数再包一层就好了。 function printHello(delay) { let timer = null; // 执行函数包在内部,这样 timer 相对于它又是全局变量了 function fn() { console.log('hello'); timer = setTimeout(fn, 5000); } fn(); setTimeout(() => { if (!timer) return; clearTimeout(timer); console.log('clear'); }, delay); }
1 1

相关推荐

牛客网
牛客企业服务