What is the Ember implementation of setInterval and clearInterval

Ember has the following setTimeout implementation, which is recommended for developers to use because the code is added to the run loop, which has advantages for tests.

  Ember.run.later((function() { console.log("will run once after 1000"); }), 1000); 

Is there a similar Ember replacement for setInterval and, in meaning, clearInterval (which is used to override setInterval)? I need to run someFunc every 1000 ms

 this.intervalId = setInterval(this.someFunc.bind(this), 1000); 
+7
source share
2 answers

I don't know any equivalent, but I use code like this to have functionality:

 var Poller = Ember.Object.extend({ _interval: 1000, _currentlyExecutedFunction: null, start: function(context, pollingFunction) { this.set('_currentlyExecutedFunction', this._schedule(context, pollingFunction, [].slice.call(arguments, 2))); }, stop: function() { Ember.run.cancel(this.get('_currentlyExecutedFunction')); }, _schedule: function(context, func, args) { return Ember.run.later(this, function() { this.set('_currentlyExecutedFunction', this._schedule(context, func, args)); func.apply(context, args); }, this.get('_interval')); }, setInterval: function(interval) { this.set('_interval', interval); } }); export default Poller; 

Then you create an instance of poller: var poller = Poller.create() , and then you can play with poller.start() and poller.stop() +, setting the interval through poller.setInterval(interval) .

In my code, I did more or less like this (polling reports every 10 seconds):

 _updateRunningReport: function(report) { var poller = new Poller(); poller.setInterval(this.POLLING_INTERVAL); poller.start(this, function() { if (report.isRunning()) { this._reloadReport(report); } else { poller.stop(); } }); eventBus.onLogout(function() { poller.stop(); }); }, 

Hope this helps ...

+8
source share

Another option is to use the ember-poll add -on . Inside, it does the same thing as the @andrusieczko Poller object (both take into account the Ember Run Loop loop). From the perspective of an Ember developer, you get access to the poll service.

Just install the add-in: npm install ember-poll --save-dev .


Example:

 import Ember from 'ember'; export default Ember.Route.extend({ poll: Ember.service.inject(), setupController() { this._super(...arguments); this.get('poll').addPoll({ interval: 1000, label: 'my-poll', callback: () => { //do something every second } }); }, actions: { willTransition() { this.get('poll').clearPollByLabel('my-poll'); } } } 
0
source share

All Articles