0

Hi I am trying to create a JS object that would serve me as a timer for my project but I have run into one problem.

const timer = {
 timePassed : 0,
 countStart : Date.now(),
 display : document.querySelector(".timer-display-value"),
 updateTimer : function() {
  let delta = Date.now() - this.countStart;
  this.timePassed = Math.floor(delta / 1000);
  this.display.textContent = this.timePassed;
 },
 startTiming : setInterval(
    this.updateTimer
    ,500
 ),
 start : function() {
   this.countStart = Date.now();
   this.startTiming();
 },
 stop : function() {
   clearInterval(timer.startTiming());
 }
};

With that code when I am trying to call the startTiming method i get an error that it is not a function. I have already spent some time trying to fix it and i have no idea what the problem may be.

MarkusSPE
  • 51
  • 7
  • `startTiming` is not a function. Do you want to make it one? Also I don't think that `stop` should call that function. Better put `this.startTiming = setInterval(…)` inside the `start` method. – Bergi Mar 24 '18 at 20:47
  • Well the main goal for me was to make two methods one starting the interval and second one clearing it. So i figured that i needed a way to reference the setInterval to be able to clear it that is why I am trying to add it as a separate method to the object. Is there a better way? – MarkusSPE Mar 24 '18 at 20:55
  • The issue is not only self-referencing, but also that `setInterval` does not return a function. It returns an Interval ID that can be used to clear an interval. That is why you are getting the error "startTiming is not a function". You need to make `startTiming` a function that calls and stores the result of `setTimeout` instead of `startTiming: setTimeout(...)`. The question was marked as duplicate as I was working on a solution otherwise I would have posted this as an answer. Here's a working JSFiddle: https://jsfiddle.net/grammar/gqsyak16/6/ – grammar Mar 24 '18 at 20:56
  • @KonradP The setInterval id you want to reference is a data property (just like `timePassed` or `countStart`) not a method. You want to initialise it inside your `start()` method, not when creating the `timer` object. – Bergi Mar 24 '18 at 21:21

0 Answers0