Reply
Setinterval on object method.
Replies: 0   Views: 1421  Subscribers: 0

Posted by reece · 30-06-2012 - 22:31

Edited by reece · 12-11-2012 - 05:03
setInterval is a built in function in javascript that you can use to have a function get called continuously at a set interval which is measured in milliseconds.

When using setInterval on an object in javascript you are not able to use the keyword 'this' because for some reason it has a different context, as a result the function is likely to only run once or not at all.

I discovered this myself after having some issue with the function only being called once or sometimes not at all, and after doing a little googling discovered in the mozilla documentation that in setInterval this has a different or no context.

The issue is entitled "the 'this' problem". Though the issue i found was on the documentation of setTimeout, it applies also to setInterval. Here is an extract of what it had to say:

­
MDN
Code executed by setTimeout() is run in a separate execution context to the function from which it was called. As a consequence, the this keyword for the called function will be set to the window (or global) object, it will not be the same as the this value for the function that called setTimeout. This issue is explained in more detail in the JavaScript reference.­
There are however a few ways around this issue. The first approach is to delegate responsibility to a function outside of the scope of the object, in this way the internals of setInterval is not concerned with the object and calls a regular function which in turn can use the object. ­
// set the interval by passing the object to refresh() function.
setInterval(function () {
	refresh(obj);
}, 2000);

// call the method in your object
function refresh(obj)
{
	obj.doSomething();
}­
The other approach is to use javascript proxy function. ­
setInterval($.proxy(obj.refresh,obj), 2000);­
Both are perfectly valid approaches, though the proxy approach would use less lines of code. Just as a footnote, as intervals are set using milliseconds, my usage of 2000, would equate to 2 seconds, just multiply the number of seconds you need by 1000. References: ­The 'this' problem­ I originally came across the resource from the stack overflow question posed by another user some time ago. The original SO can be found ­here­ where the solution posed by the user CMS.­