setTimeout in the same function to whom it is calling?

I have learned that the setTimeout function runs once and the setInterval runs continuously after the specified time but when I am calling the setTimeout function in the same function it is calling it is behaving like the setInterval but when I am doing setInterval instead of set timeout it is behaving weird.
can anyone tell me what is happening to setTimeout and setInetval in function?

code with setTimeout

function hello(){
  console.log("hello");
  setTimeout(hello,2000)
}
hello()

code with SetInterval

function hello(){
  console.log("hello");
  setInterval(hello,2000)
}
hello()

Thanks in Advance

4 thoughts on “setTimeout in the same function to whom it is calling?”

  1. In first example:
    Whenever hello method is called it registers a new timer to call hello after 2000ms. So, there will always be single call after 2000ms.

    In second example:
    Whenever hello is called it registers a new setInterval every time without terminating the previous setInterval which will result in new setInterval getting registered every time and you will get multiple logs on the console which will keep increasing every time hello is called.

    Reply
  2. The difference is that when there is setTimeout in the function, the asynchronous call stack will add a new function to be executed in the asynchronous call stack every time after the function is executed. Although setinterval also adds a function to be executed in the asynchronous call stack, the currently added function to be executed contains a setinterval, which means that there will be an exponential number when setinterval is executed The reason of "hello" output

    You can execute the following code to facilitate your understandingļ¼š

    let count = 0
    
    function hello() {
        console.log("hello");
        console.log("count:" + count++);
        setInterval(hello, 2000)
    }
    
    hello()
    Reply
    • setTimeout allows us to run a function once.
    • setInterval allows us to run a function repeatedly.

    In your example, only one setTimout always exists, but setInterval creates one every 2000ms.

    Reply
  3. In setInterval your your function will call in every 2 seconds as per your code.

    function hello(){
      console.log("hello");
      setInterval(hello,2000)
    }
    hello()
    

    Here Hello() called . And after 2 second again hello called with another setInterval(). It will called again hello method().
    Though javascript is asynchronous, It will call thousands of hello() after sometime.
    So this is not the right way to write setInterval.

    You can write like this.

    function hello() {
       console.log("hello");
    }
    setInterval(hello, 2000)
    

    Now setInterval will call in every 2 seconds.

    Comment below, if you have any doubt

    Reply

Leave a Comment