I've a doubt in one output question.
Expectation -> I need to print numbers in a range (from , to) at every 1 second gap. I need to implement this in both ways setTimeout & setInterval. (Question link)
I've made 3 methods -
- printNumbers(from ,to) -> Using setTimeout or setInterval, it is not working fine (My doubt is in this method, Why it is not taking gap of 1 second)
- printNumbersT(from ,to) -> Using setTimeout, it is working fine
- printNumbersI(from ,to) -> Using setInterval, it is working fine
printNumbers(from ,to) is printing all numbers at same time without a gap of 1 second. I want to know how is this working, why it is not taking a gap of 1 second. I need explanation for this.
// ❌ not working fine (My doubt is in this method, Why it is not taking gap of 1 second)
const printNumbers = (from, to) => {
for (let i = from; i < to; i++) {
setInterval(() => console.log(i), 1000);
}
}; //
// ✅ working fine
const printNumbersT = (from, to) => {
let current = from;
const fun = () => {
console.log(current);
if (current < to) {
current++;
setTimeout(fun, 1000);
}
};
setTimeout(fun, 1000);
};
// ✅ working fine
const printNumbersI = (from, to) => {
let current = from;
const fun = () => {
console.log(current);
if (current < to) {
current++;
} else {
clearInterval(timerId);
}
};
const timerId = setInterval(fun, 1000);
};