Possible Duplicate:
setInterval() only running function once
I’m using the following script to understand the concept of function context. I’m excepting the alerts to start from 20 onwards and repeat. But it goes quite after displaying 20.
When using call method and providing the o2, it should get the value 20 and repeat from there on.
<script type="text/javascript">
var o2 = {
local: 20
}
var local=0;
function someFuncObject(){
alert('Thats method object again ' + this.local++);
}
// window.setInterval(someFuncObject, 2000); //This works perfect!!!
window.setInterval(someFuncObject.call(o2), 2000); // This does not, why?
</script>
On the otherhand if I use window.setInterval(someFuncObject, 2000); it works fine and repeats again and again. What’s the problem?
someFuncObject.call(o2)actually calls the function. This means, what gets passed intosetIntervalis what is returned fromsomeFuncObject(). WhatsetIntervalexpects as parameter is a function itself, not what the function returns.If you want to control the value of
thisinsidesomeFuncObject, you can use an anonymous function like: