How can I output an automatic timer using Handlebars?


#1

I’ve made a function which works as a timer and executes every second. When I console log the output of the function, it works fine, but it doesn’t update graphically. This is my code:

In the model:

timer: function(){
   var model = this;
   return setInterval(function(){
      var start = model.get('startTime');
      var end = Date.now();
      var difference = end - start;
      console.log(difference);
      return difference;
 }, 1000);

In handlebars:

{{model.timer}}


#2

Where is this function? Is it in a component, a helper, or somewhere else? If you want it to work from a component, this should probably be a computed property. If it’s in the route, them timer needs to be returned in the model hook. Including the rest of your code would be helpful here.


#3

The function is in the model. When I console log’d “difference”, it outputted the correct values. The function calls itself whenever it lands on the page which has the model.timer handlebars.

This is the only relevant code I have.


#4

Basically you need to update a dependent property on your model, in this case you want to update the difference so that the template knows something has changed.

Here is a working example that you can play with: https://ember-twiddle.com/058adb38832173c7596e

Code snip from example.

import Ember from 'ember';

export default Ember.Controller.extend({
  delta: 0,
  _interval: null,
  startTime: null,
  timer: Ember.computed('delta', function() {
    const that = this;
    if (this._interval === null) {
      this.set('startTime', Date.now());
      this._interval = setInterval(function() {
        const start = that.get('startTime');
        that.set('delta', Date.now() - start);
      }, 100);
    }

    return this.get('delta');
  }),
});

To make this example more robust I would check if the object was destroyed in the set interval and wrap the set delta in an ember run. However, I’ll leave you to this since it should make for a glorious learning experience :slight_smile:

Hopefully this is just enough you up and running with what ever you are building.

Have fun!

–Ben


#5

This is just what I was looking for, thank you!


#6

How can we stop this timer by setting a duration