Question: I've written some code that when you click a button it adds an instance of a function to an array,

```
var objects = [];

$(document).on("click", ".addButton", function(){
    objects.push(new newObject(1));
});

function newObject(amount){
    setInterval(function(){ 
        addValue(amount);
    }, 1000);
}

```

So then every second each new object created keeps running the addValue function every second adding the amount.

The problem is when I try and destroy that function with objects.pop() it deletes the object but the setInterval doesn't stop running. 

How do I make it destroy everything in that function and stop it from running?

Answer: 
There is nothing quite like that in JS for setInterval. I would suggesting declaring a method to handle clean up. 

```
// "Class" declaration    
function newObject(amount) {
    var id = setInterval(function() { 
        addValue(amount);
    }, 1000);

    this.kill = function() {
        clearInterval(id);
    }
}

// "Public" api for the data structure
var objects = [];

function addNewObject() {
    objects.push(new newObject(1));
}

function destroyLastObject() {
    objects.pop().kill();
}

// Event bindings
$(document).on("click", ".addButton", addNewObject);
$(document).on("click", ".removeButton", destroyLastObject);

```

Completely untested, but along these lines should work.

*EDIT*

This, imo, is a great resource for learning about different patterns within javascript - long but well well worth the read: <https://addyosmani.com/resources/essentialjsdesignpatterns/book/>
You got to find something to check against to clear the interval. I am clearing based on array length. It only executes once. 

```js
// you got to find something to check against to clear the interval
var objects = [];

document.addEventListener("click", function(){
  console.log('click');
    objects.push(new newObject(1));
});

function newObject(amount){

 var interval= setInterval(function(){ 

         if(objects.length !==0){
        clearInterval(interval);
        }
    }, 1000);
}
```