Preety straight forward question, though I can't find the answer anywhere I tried these two ways:
setInterval(function(){object/*or this*/.method()},500)
and
setInterval('object/*or this*/.method()',500)
Preety straight forward question, though I can't find the answer anywhere I tried these two ways:
setInterval(function(){object/*or this*/.method()},500)
and
setInterval('object/*or this*/.method()',500)
The difference between your 2 ways for passing a function to setInterval
is whether you want to pass your function as refrence of just copy of it. Allow me to explain it by example:
var obj = {
testMethod: function () {
console.log('function (testMethod): intial output');
}
}
setInterval(function () {
obj.testMethod()
}, 1000);
obj.testMethod = function () {
console.log('function (testMethod): changed output');
}
when you run this code, the result 'll be execution of the modified version of testMethod
. Because here you dont copy the function! Instead, you refer to it. So whenever function implementation is changed, the last modified version is executed.
var obj = {
testMethod: function () {
console.log('function (testMethod): intial output');
}
}
setInterval(obj.testMethod, 1000);
obj.testMethod = function () {
console.log('function (testMethod): changed output');
}
Here all you do is you are passing a copy of the last defined version of the function testMethod
to setInterval
. So whatever changes you do to testMethod
, the result of setInterval
will not be changed.
setInterval in fact expects a method as the first argument, though there is an alternative syntax where the first argument can be a string of code (not recommended by most)
If you're having issues with that code, it may have to do with the scope of 'this'
In the above code, 'this' will refer to the closure itself, and wouldn't be the same as 'this.method' occurring outside of that closure. For example, the following would work:
Whereas the following will not work (presuming instantiating the object and calling foo()):
The second example will work if we get around using 'this' within the closure (presuming instantiating the object and calling bar()):
Also be sure that setInterval is being passed the name of a function:
rather than executing a function as an argument
This last line of code is usually a mistake, unless someFunction() returns a function itself ;)