← 中文资源

简体中文版本

using 声明自动释放资源

用 using 声明配合 Symbol.dispose,在作用域退出时释放计时器,即使函数提前返回也能执行清理。

阅读英文原文

实现说明

真正干活的是类 Stopwatch和函数 sumTo,其余都是接线。 这个示例中仅有的重复出现在 for (let value = 1; value <= limit; value += 1) 里。

使用要点

  • 跑完文件,输出里会留下标记——result、disposed before this line。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 文件在加载时定义 sumTo。

主要签名是 function sumTo(limit: number)

核心语句

for (let value = 1; value <= limit; value += 1) {
  total += value;
}

代码示例

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');