从Frontendmasters课程中学习JavaScript "异步性 "的一些基本概念。JavaScript。困难的部分,v2
我得到的是 练习(挑战五):
设立一个职能部门
limitedRepeat
该控制台记录"hi for now"
每秒钟,但只有5秒钟。研究如何使用clearInterval()
如果你不知道如何做。
而这个功能的占位符如下。
function limitedRepeat() {
//CODE HERE
}
我能够解决它,如下(2个版本)。
版本一
function limitedRepeat() {
var totalLogs = 0;
var logFunc = setInterval(myTimer, 1000)
function myTimer() {
if(totalLogs < 5){
console.log("hi for now");
totalLogs++;
} else {
clearInterval(logFunc);
}
}
}
limitedRepeat(); // should log (every second, for 5 seconds): hi for now
第二版
function limitedRepeat(totalLogs) {
console.log("hi for now");
var timery = setTimeout(timerable,1000);
function timerable() {
totalLogs++;
if(totalLogs >= 5){
clearTimeout(timery);
} else {
limitedRepeat(totalLogs);
}
}
}
limitedRepeat(0); // should log (every second, for 5 seconds): hi for now
很明显,我已经改变了函数的签名。第二版因此,我很好奇是否有解决方案,利用了 setTimeout()
和 clearTimeout()
和可能的递归,不需要改变函数的签名--换句话说,对于那个由超时设置的递归调用,以某种方式记住多少次被打印到控制台的日志?
用递归的方式。
function limitedRepeat(count = 0) {
if(count >= 5) return;
console.log('hi')
setTimeout(() => limitedRepeat(++count), 1000)
}
limitedRepeat()
只要确保你在调用函数之前递增就可以了。
使用一个名为IIFE的内部函数与递归。
EDIT:如果我们把参数传递给内部函数,我们甚至不需要闭包来记忆执行的次数。
function limitedRepeat() {
const maxTimes = 5;
return (function _limitedRepeat(current) {
console.log("hi for now");
var timery = setTimeout(timerable, 1000);
function timerable() {
current++;
if (current >= maxTimes) {
return
}
_limitedRepeat(current);
}
})(0);
}
limitedRepeat();
这是我的方法。
var count = 1,
timer = setInterval(limitedRepeat,1000)
function limitedRepeat() {
console.log('Hi for now');
count++;
if(count > 5) clearInterval(timer)
}