如何在JavaScript中停止异步功能?

时间:2015-07-17 15:20:50

标签: javascript asynchronous settimeout

我有一些异步问题。我正在研究一个ECMAScript 6对象。这是一个计时器,我希望能够在倒计时期间重新启动。

这是我的工作:

export class Timer {
    constructor(sec){
        this.sec = sec;
        this.count = sec;
        this.running = false;
    }

    start() {
        this.running = true;
        this._run();
    }

    _run(){
        if(this.running){
            setTimeout(()=>{
                this.count --;
                console.log(this.count);
                if(this.count<0){
                    this.running = false;
                }
                this._run();
            }, 1000);
        }
    }

    restart(){
        this.running = false;
        /*
            Wait until _run() is done then :
        */
        this.count = this.sec;
        this.start();
    }
}

restart()函数中,如何知道_run()何时停止运行?

1 个答案:

答案 0 :(得分:2)

了解计时器是否“正在运行”的更简单方法是使用setInterval代替。

var interval = setInterval(() => updateTimer(), 10); // update every 10ms

如果interval已设置

,它正在运行
if (interval) // timer is running

停止计时器

window.clearInterval(interval);
interval = null;
// timer is no longer "running"

附加说明

  

注意创建以固定值递增的计时器

在您的代码中,您有

setTimeout(() => this.count--, 1000);

您打算每秒递减一次count财产,但这不是您将得到保证的行为。

查看这个小脚本

var state = {now: Date.now()};

function delta(now) {
  let delta = now - state.now;
  state.now = now;
  return delta;
}

setInterval(() => console.log(delta(Date.now())), 1000);

// Output
1002
1000
1004
1002
1002
1001
1002
1000

我们使用setInterval(fn, 1000)但实际间隔每次都会变化几毫秒。

如果您执行诸如将浏览器的焦点切换到其他选项卡,打开新标签等操作,那么问题会被夸大。请查看这些更多零星的数字

1005 // close to 1000 ms
1005 // ...
1004 // a little variance here
1004 // ...
1834 // switched focus to previous browser tab
1231 // let timer tab run in background for a couple seconds
1082 // ...
1330 // ...
1240 // ...
2014 // switched back to timer tab
1044 // switched to previous tab
2461 // rapidly switched to many tabs below
1998 // ...
2000 // look at these numbers...
1992 // not even close to the 1000 ms that we set for the interval
2021 // ...
1989 // switched back to this tab
1040 // ...
1003 // numbers appear to stabilize while this tab is in focus
1004 // ...
1005 // ...

因此,这意味着您无法依赖setTimeout(或setInterval)函数每1000 ms运行一次。 count将根据各种因素递减多少变化。

要解决此问题,您需要使用delta。这意味着在计时器的每个“勾号”之前,您需要使用Date.now获取时间戳。在下一个刻度线上,采用新的时间戳并从新时间戳中减去之前的时间戳。那是你的delta。使用此值,将其添加到Timer的总ms中,以获得计时器运行的精确毫秒数。

然后,所有时间敏感值将是总累积ms的投影/计算。

在您的情况下,假设您的count10开始。如果您想要-11000 ms计算一次,则可以执行

function update() {
  // update totalMs
  this.totalMs += calculateDelta();
  // display count based on totalMS
  console.log("count %d", Math.ceil(this.count - this.totalMs/1000));
}

这是一个示例ES6计时器,它实现了可能对您有帮助的delta函数

class Timer {
  constructor(resolution=1000, ms=0) {
    this.ms = ms
    this.resolution = resolution;
    this.interval = null;
  }
  delta(now) {
    let delta = now - this.now;
    this.now = now;
    return delta;
  }
  start() {
    this.now = Date.now();
    this.interval = window.setInterval(() => this.update(), this.resolution);
  }
  reset() {
    this.update();
    this.ms = 0;
  }
  stop() {
    this.update();
    window.clearInterval(this.interval);
    this.interval = null;
  }
  update() {
    this.ms += this.delta(Date.now());
    console.log("%d ms - %0.2f sec", this.ms, this.ms/1000);
  }
}

创建一个50 ms“分辨率”的新计时器。所有这些意味着定时器显示每50毫秒更新一次。您可以将此值设置为任何值,计时器仍将保持准确的值。

var t = new Timer(50);
t.start();

要模拟重置,我们可以创建一次性超时,以便您可以看到重置工作

// in ~5 seconds, reset the timer once
setTimeout(() => t.reset(), 5000);

以下是暂停计时器

的演示
// in ~10 seconds, pause the timer
setTimeout(() => t.stop(), 10000);

你也可以恢复计时器

// in ~12 seconds, resume the timer (without reset)
setTimeout(() => t.start(), 12000);

您可以随意startstopreset计时器

这是ES6(上面)转换为ES5,因此您可以看到代码在runnable片段中工作。打开控制台,然后单击运行代码段

"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Timer = (function () {
  function Timer() {
    var resolution = arguments.length <= 0 || arguments[0] === undefined ? 1000 : arguments[0];
    var ms = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];

    _classCallCheck(this, Timer);

    this.ms = ms;
    this.resolution = resolution;
    this.interval = null;
  }

  Timer.prototype.delta = function delta(now) {
    var delta = now - this.now;
    this.now = now;
    return delta;
  };

  Timer.prototype.start = function start() {
    var _this = this;

    this.now = Date.now();
    this.interval = window.setInterval(function () {
      return _this.update();
    }, this.resolution);
  };

  Timer.prototype.reset = function reset() {
    this.update();
    this.ms = 0;
  };

  Timer.prototype.stop = function stop() {
    this.update();
    window.clearInterval(this.interval);
    this.interval = null;
  };

  Timer.prototype.update = function update() {
    this.ms += this.delta(Date.now());
    console.log("%d ms - %0.2f sec", this.ms, this.ms / 1000);
  };

  return Timer;
})();

var t = new Timer(50);
t.start();

// in ~5 seconds, reset the timer once
setTimeout(function () {
  return t.reset();
}, 5000);

// in ~10 seconds, pause the timer
setTimeout(function () {
  return t.stop();
}, 10000);

// in ~12 seconds, resume the timer (without reset)
setTimeout(function () {
  return t.start();
}, 12000);