Ember.run.later
只运行一次函数。文档中说得很清楚
另外,您使用非常旧版本的 ember 吗?Ember.run.later
已过时,您应该使用部分导入import { later } from '@ember/runloop';
代替
至于你的任务,至少有两种方法
使用 ember-concurrency 插件
安装ember-concurrency并写入控制器:
import { task, timeout } from 'ember-concurrency';
export default Controller.extend({
infiniteTask: task(function* () {
while(true) {
this.functionThatIsRunningEachTwoSeconds();
yield timeout(2000);
}
}).drop(),
});
模板:
{{#if infiniteTask.isIdle}}
<button onclick={{perform infiniteTask}}>Start</button>
{{else}}
<button onclick={{cancel-all infiniteTask}}>Stop</button>
{{/if}}
这个插件在很多情况下都有帮助,阅读它的文档来了解你为什么需要它
创建一个递归调用自身的函数
这是一种经典的 JS 方法来重复一些动作,但在 vanilla JS 中我们使用setTimeout
而不是 ember 的later
.
import { later, cancel } from '@ember/runloop';
export default Controller.extend({
infiniteFuction() {
this.functionThatIsRunningEachTwoSeconds();
this.set('infiniteTimer', later(this, 'infiniteFuction', 2000));
},
startInfiniteFunction() {
//clear timer as safety measure to prevent from starting few
//"infinite function loops" at the same time
cancel(this.infiniteTimer);
this.infiniteFuction();
},
stopInfiniteFunction() {
cancel(this.infiniteTimer);
this.set('infiniteTimer', undefined);
}
});
模板:
{{#unless infiniteTimer}}
<button onclick={{action startInfiniteFunction}}>Start</button>
{{else}}
<button onclick={{action stopInfiniteFunction}}>Stop</button>
{{/unless}}