The variable lastTime
here is captured via closure. This means it is kept alive beyond the scope of the function it is defined in.
A closure gets created anytime an anonymous function body references a variable outside of its own scope. Closures are extremely useful in JavaScript, as they allow you to maintain state without exposing it all globally.
To give a simplified example,
function foo() {
var count = 0;
setInterval(function bar() {
console.log(count++);
}, 100);
}
By closing over the count
variable here, I can use it in setInterval
without exposing count
to the global scope as I would otherwise have to do.