2

I'm trying to use "setInterval" and "clearInterval" functions inside js objects created with "new" operator.

html:

<button onclick="testList.push(new Test());">run</button>

js:

Test = function(){
   this.y = 0;
   this.dy = 10;
   that = this;
   this.interval = setInterval(function(){
        that.y += that.dy;
        if (that.y>300){
            console.log(that.y);  //prints y in console
            clearInterval(that.interval);
        }
   }, 10);
}

JFIDDLE

When I click the "run" button once this works as I expect. But when I click the "run" button multiple times before a previous interval is not cleared (when click the button multiple times quickly), then intervals are not cleared and y is incremented infinitely. What is the mistake I'm making here?

Thank you in advance...

Sampath Liyanage
  • 4,339
  • 23
  • 38
  • Wondering why you are using a function expression to create the constructor rather than a function declaration. – RobG Nov 01 '14 at 12:22
  • @Robg Any disadvantages of using a function expression here (other than the function is not defined until this line is executed)? – Sampath Liyanage Nov 01 '14 at 12:35
  • 1
    That's about it, there is a lot written here: [*var functionName = function() {} vs function functionName() {}*](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname). I prefer to see declarations over expressions, where expressions are used for assignments only. But others prefer to use expressions everywhere so everything is an assignment. Horses for courses… ;-) – RobG Nov 03 '14 at 02:45

1 Answers1

2

You are creating a global variable that which overwites previous Test instance references:

that = this;

You should use var keyword when you declare variables:

var that = this;
dfsq
  • 182,609
  • 24
  • 222
  • 242