I recently came across this code snippet:
class CentralControlUnit {
private devices: Device[] = [];
constructor() {
// Adding a new device MobileDevice
this.devices.push(new MobileDevice(this));
}
activate() {
for (var i= 0; i < this.devices.length; i++) {
// Activating the device
this.devices[i].switchOn();
}
window.setTimeout(() => this.activate(), 1000);
}
triggerAlarm(alertMessage: string) {
console.log('Alert! ' + alertMessage);
}
}
var ccu = new CentralControlUnit();
ccu.activate();
I'm curious why
window.setTimeout(() => this.activate(), 1000);
doesn't create an infinite loop.
From what I understand, ccu.activate()
iterates through each device
in devices
first and then schedules another call to activate
using window.setTimeout
, which repeats every 1
second.
Check out Listing 3-3. Delegation in Pro TypeScript: Application-Scale JavaScript Development for more details.