August 2016
Beginner to intermediate
847 pages
17h 28m
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.