2

I got a bit confused about a code snippet that I took from the react.js docs: http://facebook.github.io/react/docs/reusable-components.html

But I converted it to a general js case:

var SomeFunc = function(){
    this.intervals = []; 
    this.setInterval = function(){
        this.intervals.push(setInterval.apply(null, arguments));
    }; 
    var self = this; 
    this.cleanup = setTimeout(function(){ 
        self.intervals.map(clearInterval);
    }, 3000); 
}

var someFunc = new someFunc(); 
someFunc.setInterval(this.tick, 1000); 
someFunc.cleanup();  

I'm confused by the following line:

this.intervals.push(setInterval.apply(null, arguments));

When I console.log the the argument of push, it returns 1.
Can someone explain what actually gets stored in this array?
The cleanup works, so why does the array show the array index number (+1?) instead of what is actually stored in the array?

React.js jsfiddle:
http://jsfiddle.net/xsjfq5ex/2/

2 Answers 2

6

setInterval returns the interval ID, so that is what gets stored in your array:

Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. Returns an intervalID.

intervalID is a unique interval ID you can pass to clearInterval().

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's it. Accept in a few minutes.
2

You're creating a property called setInterval on the object whose constructor is SomeFunc. The property is a function that simply delegates the task of creating an interval to the global setInterval, but also keeps track of the ones it creates.

Using setInterval.apply(null, arguments), you are essentially calling the global setInterval, and passing the arguments down to that (which would be the function to execute and the interval in milliseconds). The null indicates what this will reference inside the body of the function.

setInterval() will create the interval and return the ID assigned to that interval; this ID is what you are storing in the array. When you call cleanup, you are mapping the array via clearInterval, which accepts the ID of the interval to clear (and in this case, is passed in via map's callback.

So in simple terms, you're creating an intermediate layer to store the intervals as if they're "assigned" to the object you created. This makes them easier to clear when you're finished.

2 Comments

Why use apply() instead of simply calling the regular setTimeout(cb,1000)?
@Pier It seems to be a choice the original author of the code made. That way, he doesn't have to specify the callback and interval time as parameters to the this.setInterval function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.