An account object has a balance property and a method schedule to simulate a credit and a debit after scheduled time:
// account has $100 balance at start.
var account = { balance: 100 };
account.schedule = function () {
/* Schedule a $100 credit after 1/2 second.
Use arrow function for timer callback.*/
setTimeout( () => {
// Credit $100
this.balance += 100;
/* Schedule a $200 debit after
1/2 second. Use regular function
for timer callback.*/
setTimeout( function() {
// Debit $200
this.balance -= 200;
}, 500 );
}, 500 );
};
The account object is created with $100 balance. The schedule method schedules a $100 credit after a 1/2 second (500ms) timeout. The callback arrow function credits $100 and then schedules a $200 credit after another 1/2 second (500ms) timeout, notice that this time the timer callback function is a regular function.
This question highlights a very important difference between arrow function and regular function related to how 'this' is bound. Let's call the account.schedule and check the balance after 2 seconds.
// Call schedule() to schedule credit/debit
account.schedule();
// Check balance after 2 seconds
setTimeout( function() {
console.log(account.balance);
}, 2000 );
What do you think would be logged as account.balance (after 2 seconds) above?