javascript - 如何使用 Ember.run.later 实现秒表倒计时

标签 javascript algorithm ember.js

解决方案归结为“如何清除 Ember.run.later 的间隔”

  class CountdownTimer {

  constructor() {
    this.counterContinue = false;
  }

  start() {
    this.counterContinue = true;
    this.decreaseCounterLoop();
  }

  stop() {
    this.counterContinue = false;
  }

  decreaseCounterLoop() {
    Ember.run.later(this, function() {
      //do work

      if (this.counterContinue) {
        this.decreaseCounterLoop();
      }
    }, 1000);
  }
}

我尝试实现一个可以随意开始和停止的倒数计时器。但目前这有一个错误。

我调用 stop(),然后再次快速调用 start(),以便 decreaseCounterLoop 开始循环两次 一秒钟。

最佳答案

有许多不同的方法可以解决此问题,但您发布的代码中的问题是调用停止时超时未清除 - 这意味着,正如您所注意到的,您最终可能会运行两个循环。

class CountdownTimer {

    constructor() {
      this.timeout = null;
    }

    start() {
      this.decreaseCounterLoop();
    }

    stop() {
      clearTimeout(this.timeout);
    }

  decreaseCounterLoop() {
    this.timeout = setTimeout(this, function() {
      //do work
      this.decreaseCounterLoop();
    }, 1000);
  }

}

我没有使用过 Ember,但同样的逻辑应该可以使用 Ember.run.cancel .

关于javascript - 如何使用 Ember.run.later 实现秒表倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30485112/

相关文章:

javascript - 检测单页应用程序的页面变化 JS

ember.js - 在 Ember.js 中创建灯箱路线

javascript - 为什么对象原型(prototype)显示为 html 属性?

javascript - 捕获两个并行运行的异步函数都执行完毕的时刻

javascript - 使用 JavaScript 显示 Facebook 群组成员的当前数量

algorithm - 从给定的二分图中找到所有最大完全二分图

javascript - 获取服务器设置的客户端cookie

algorithm - 是否有一种算法可以安全地将一条消息分成 x 个部分,至少需要 y 个部分才能重新组合?

c# - 查找已排序整数数组的交集

javascript - 为副作用而导入的 ES6 模块的公认做法?