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
In the
call1, we call it "closure". "Closure" is the keyword for what you are looking for.For short, it is supposed the
timerwill be terminated when thecall1is done. However, thecall1returns a function which references to thetimer. So thetimeris 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.