using Declarations Dispose Resources
Use a using declaration with Symbol.dispose to release a stopwatch at scope exit, even when the surrounding function returns early.
Code
class Stopwatch implements Disposable {
private readonly startedAt = Date.now();
constructor(private readonly label: string) {}
[Symbol.dispose](): void {
const elapsed = Date.now() - this.startedAt;
console.log(this.label + ' took ' + elapsed + 'ms');
}
}
function sumTo(limit: number): number {
using watch = new Stopwatch('sumTo');
let total = 0;
for (let value = 1; value <= limit; value += 1) {
total += value;
}
return total;
}
console.log('result', sumTo(100_000));
console.log('disposed before this line');How it works
Stopwatch implements Disposable with a [Symbol.dispose]() method that logs elapsed milliseconds, and sumTo acquires it with a using watch declaration so disposal fires at scope exit — even though the function returns first.
for (let value = 1; value <= limit; value += 1) is the loop doing the per-item work.
Putting it to use
Signature: function sumTo(limit: number)
The output order makes the semantics plain: result 5000050000 from the return value, then the sumTo took Nms disposal line, and only afterwards disposed before this line — proof the cleanup ran at scope exit, not at script end.
Core lines
for (let value = 1; value <= limit; value += 1) {
total += value;
}
Interactive Tools for This Topic
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `sumTo` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.