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
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 previoussetInterval
which will result in newsetInterval
getting registered every time and you will get multiple logs on the console which will keep increasing every timehello
is called.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:
setTimeout
allows us to run a function once.setInterval
allows us to run a function repeatedly.In your example, only one
setTimout
always exists, butsetInterval
creates one every 2000ms.In
setInterval
your your function will call in every 2 seconds as per your code.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 ofhello()
after sometime.So this is not the right way to write setInterval.
You can write like this.
Now setInterval will call in every 2 seconds.