It's beginner's question. I'm trying to understand setTimeout. I want to print each number after a delay of 2 seconds. However, I can only delay the whole function, not the numbers. Can anyone tell me how to do it?
function print() {
for (let i = 10; i >= 0; i--) {
console.log(i);
}
}
setTimeout(print, 2000);
You need to use the setTimeout inside the print method (inside the for), and give a different delay for each iteration.
function print() {
for (let i = 10; i >= 1; i--) {
setTimeout(() => {
console.log(i);
}, 2000 * (10 - i));
}
}
print();
Another approach is using setInterval. It is more natural for this task then setTImeout.
let i = 10;
const interval = setInterval(() => {
console.log(i);
i--;
if(i === 0){
clearInterval(interval);
}
}, 2000);
setTimeout here will delay all the function and if I get what you want to do is to print each number in 2s delay. ill recommend using Promises and async function. here is a solution with only setTimeout
function print(i){
console.log(i)
if(i>0){
setTimeout(()=>{print(i-1)},2000)
}
}
print(10)