demo · v131
build your own disposable: a stopwatch with Symbol.dispose
Any object implementing [Symbol.dispose]() can be used with using. Below: a stopwatch class that starts on construction, stops when disposed, and a try-it that runs it inside a scoped block. Watch the timer auto-stop when the scope ends.
Symbol.dispose: ?
DisposableStack: ?
AsyncDisposableStack: ?
stopwatch (scoped)
0.000s
stopwatch (shared)
0.000s
the api
class Stopwatch {
constructor(name) {
this.name = name; this.start = performance.now();
}
elapsed() { return ((performance.now() - this.start) / 1000).toFixed(3) + "s"; }
[Symbol.dispose]() {
console.log(this.name, "stopped at", this.elapsed());
}
}
{
using sw = new Stopwatch("scope");
// ... do work ...
} // sw[Symbol.dispose]() runs here, automatically