I have two similar functions using setTimeout() but it is giving me two different results

63 Views Asked by At

Here in the function calls call1 and call2 I am trying to achieve the same thing i.e print the values with a delay of 1000 seconds .But what I notice is that in call1() the variable timer persists between different function calls whereas , in call2 the variable timer in the first call is not present when the call2 is called for the second time . why does this happen ? It would be helpful if you provide me with some resource so that i can learn about this code :

const myFunction= (d) => {
    let timer ;
    return function(){
        if (timer) console.log("funCall1 : timer is still present");else console.log("funCall1 : timer not present")
        timer = setTimeout(()=>{
            console.log("funCall1 : inside setTimeout")
        },d)
    }
}

const call1=myFunction(1000)

function call2(){
  let timer;
  if(timer)
  console.log("funCall2 : timer is present")

  timer = setTimeout(()=>{
    console.log("funCall2 : abc")
  },1000)
}

call1()
call1()
call1()

call2()
call2()
call2()

I compiled the above code using the online compiler programiz:JSCompiler

OUTPUT

funCall1 : timer not present
funCall1 : timer is still present
funCall1 : timer is still present
funCall1 : inside setTimeout
funCall1 : inside setTimeout
funCall1 : inside setTimeout
funCall2 : abc
funCall2 : abc
funCall2 : abc
1

There are 1 best solutions below

0
Khoa On BEST ANSWER

In the call1, we call it "closure". "Closure" is the keyword for what you are looking for.

For short, it is supposed the timer will be terminated when the call1 is done. However, the call1 returns a function which references to the timer. So the timer is not terminated. That context is called "closure".

Just note this is quick overview for what happened. For better understanding, you can google dedicated resource for explaining what "closure" is in JavaScript.