0

New Javascript student here. Currently, this is the code that I have

 function trial(number) {
    let arr = [11, 4, 5]
    console.log("Number:", number)
    setTimeout(() => {
        for (let nums in arr) {
            console.log("Num", arr[nums])
            if (arr[nums] == number) {
                console.log("A")
            } else {
                console.log("B")
            }
        }
    }, 1000)
}
trial(5) 

when I input trial([11]) it will wait for 1 second and gives all 3 results. How do I make it so that it will wait 1 second - print Num 11 A, wait another second - Num 4 B and finally another second for Num 5 B? Thanks!

zhulien
  • 5,145
  • 3
  • 22
  • 36
of131
  • 13
  • 1

1 Answers1

0

You can use setInterval.

function trial(number) {
  let arr = [11, 4, 5]
  console.log("Number:", number)
  let i = 0;
  let id = setInterval(() => {
    if(i === arr.length) return clearInterval(id);
    const num = arr[i++];
    console.log("Num", num)
    if (num == number) {
      console.log("A")
    } else {
      console.log("B")
    }
  }, 1000)
}
trial(11);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80