How can I output an automatic timer using Handlebars?

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 =;
      var difference = end - start;
      return difference;
 }, 1000);

In handlebars:


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.

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.

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:

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._interval = setInterval(function() {
        const start = that.get('startTime');
        that.set('delta', - 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!


1 Like

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

How can we stop this timer by setting a duration