TomDev
TomDev

Reputation: 287

How to print number after a delay in JS

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);

Upvotes: 1

Views: 1974

Answers (4)

azendh
azendh

Reputation: 931

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);

Upvotes: 5

Niklesh Raut
Niklesh Raut

Reputation: 34914

Another way to do this by setInterval

let limit = 10
console.log('start')
let interval = setInterval(()=>{
console.log(limit--)
if(!limit){
  clearInterval(interval)
  console.log('end')
}
},2000)

With immediate start from 10 without 2 seconds wait.

let limit = 10
console.log('start')
const executeLogic = () =>{
  console.log(limit--)
}
executeLogic()
let interval = setInterval(()=>{
  executeLogic()
  if(!limit){
    clearInterval(interval)
    console.log('end')
  }
},2000)

Upvotes: 2

Elay Gelbart
Elay Gelbart

Reputation: 88

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)

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

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();

Upvotes: 7

Related Questions