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

Viewed 30

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 -

  1. 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)
  2. printNumbersT(from ,to) -> Using setTimeout, it is working fine
  3. 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);
};

code snippet

2 Answers

setInterval and setTimeout are asynchronous, as said in mdn

setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.

In your for loop you are adding synchronously n function calls to the end of the stack, so they will be fired aproximately at the same time. To fix this you could use a promise and await its return, or you can change the delay.

const printNumbers = (from, to) => {
    for (let i = from; i < to; i++) {
        setTimeout(() => console.log(i), 1000 * i);
    }
}; 

Its failing because setInterval is expecting a function but your passing an object. complete the function with console.log within and it should work.

const printNumbers = (from, to) => {
    for (let i = from; i < to; i++) {
        setInterval(() => {
          console.log(i)
        }, 1000);
    }
}; //

printNumbers(0, 100)

Related