August 2016
Intermediate to advanced
635 pages
14h 5m
English
In implementing timers or callbacks, you need to call the handler asynchronously, mostly at a later point in time. Due to the asynchronous calls, we need to access variables from outside the scope in such functions. Consider the following example:
function delay(message) {
setTimeout( function timerFn(){
console.log( message );
}, 1000 );
}
delay( "Hello World" );We pass the inner timerFn() function to the built-in library function, setTimeout(). However, timerFn() has a scope closure over the scope of delay(), and hence it can reference the variable message.