jshbrntt
jshbrntt

Reputation: 5404

An Accurate Javascript Timer

I've been trying to make an accurate JavaScript timer using Backbone JS this is as far as I've gotten:

Source Code

It works apart from the the complete event fires twice when it shouldn't, any ideas on what I need to do to fix/improve it?

Console Output:

"tick 10 1"
"tick 10 2"
"tick 10 3"
"tick 10 4"
"tick 10 5"
"tick 10 6"
"tick 10 7"
"tick 10 8"
"tick 10 9"
"complete 10 10"
"complete 10 11"

Upvotes: 0

Views: 176

Answers (3)

Rob Sedgwick
Rob Sedgwick

Reputation: 5226

var TimerView = Backbone.View.extend({
    model: Timer,
    tagName: 'p',
    className: 'timer',
    initialize: function () {
        this.model.on('tick', function(e){console.log('tick '+e.steps+' '+e.count);}, this);
        this.model.on('complete', function(e){console.log('complete '+e.steps+' '+e.count);}, this);
        /* this.model.start(); - don't need this */
    }
});

Upvotes: 1

rgthree
rgthree

Reputation: 7273

You're calling start twice, once in your TimerView.initialize and once again after you instantiate it, meaning you have two concurrent setTimeout loops occurring (and, you're timer is moving twice as fast):

var Timer = Backbone.Model.extend({
  /* ... */
});

var TimerView = Backbone.View.extend({
  /* ... */
  initialize: function () {
    this.model.on('tick', function(e){console.log('tick '+e.steps+' '+e.count);}, this);
    this.model.on('complete', function(e){console.log('complete '+e.steps+' '+e.count);}, this);
    this.model.start(); // <-- One here
  }
});

var timer = new Timer();
var timerView = new TimerView({model: timer});
timer.start();  // <-- Another here

Upvotes: 1

Jani Hartikainen
Jani Hartikainen

Reputation: 43253

You're calling start() twice. Once after creating the model and view, and once inside your view initialize function.

Upvotes: 1

Related Questions