Reputation: 27
I am a javascript newbie, and faced a somewhat basic problem.
function expand(element){
var target = document.getElementById(element);
var h = target.offsetHeight;
var sh = target.scrollHeight;
var loopTimer = setTimeout('expand(\''+element+'\')',8);
if(h < sh){
h += 5;
} else {
clearTimeout(loopTimer);
}
target.style.height = h+"px";
}
In the code above, loopTimer variable is stated(setTimeout). However, what I am confused about is that it is simply 'stated', and not actually 'called'. To make my question clear, I rather expected just
setTimeout('expand(\''+element+'\')',8);
Because if it is stated in the variable, it seems to me that this method or function is just saved in the loopTimer, and be never used... but the code seems to work even if the loopTimer has not yet been 'called'..
Upvotes: 0
Views: 44
Reputation: 34563
The setTimeout
function returns a timeout ID that can be used to cancel the timeout later. This code is calling setTimeout
and saving its result (the ID of the new timeout) in a variable so it can be passed to clearTimeout
later.
To be clear: you're not saving the setTimeout
function in the variable; you're saving the result of calling it. Just like target
holds a DOM element returned by calling the document.getElementById
function, not the function itself.
Upvotes: 2