![Mastering JavaScript](https://wfqqreader-1252317822.image.myqcloud.com/cover/634/36702634/b_36702634.jpg)
上QQ阅读APP看书,第一时间看更新
Timers and callbacks
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.