The functions you built in the last lesson can run as often as Marco likes. One moment at the end of the night is different. Once round five is scored, his kit announces the winning team. If he corrects a typo in the last round’s scores and closes the round again, the announcement shouldn’t play a second time.
In this lesson, you’ll use a closure to make a function that runs only once. Then you’ll write a function that hands out a new ID on every call, so no two of the night’s answer sheets share one. Start with the announcement.
Let a Function Run Only Once
Marco’s script closes the last round with closeRound(), which calls announceWinner(). Closing the round again after a score correction calls announceWinner() again, and the pub hears the winner twice.
You could keep an announced flag at the top of the file and check it inside announceWinner(). But any line in the script could reset that flag, and the next thing that must happen only once would need its own flag and its own if. A closure can keep the flag private instead, inside a wrapper you can reuse for each of those functions.
The wrapper is a function called once(). You pass it a function, and it returns a new function that calls yours the first time and skips it after that:
once.js
function once(fn) {
let called = false;
let result;
return (...args) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
The arrow that once() returns is a closure over the fn parameter and two variables declared in the same call. called records whether fn has run yet, and result keeps what fn returned the first time. Every later call finds called set to true, skips the if block, and returns that same result.
Notice that called becomes true before fn runs, so the flag records that fn was tried, whether or not it succeeded. If fn throws an error on the first call, later calls still skip it, and they return undefined because result was never set. For an announcement, one attempt is what Marco wants.
The ...args in the arrow’s parameter list is a rest parameter. It collects every argument the wrapper receives into an array. Inside, fn(...args) uses spread syntax to pass that array back out as separate arguments. So once() doesn’t need to know how many arguments fn takes. It can wrap any standalone function like announceWinner(), one that works only with its arguments and the variables it closes over.