My question is basically an extension to this one:
var functionName = function() {} vs function functionName() {}.
I’ve read through all the answers, but I think I’m still missing the answer to this question:
Why does the type of function declaration matter for jQuery’s onComplete event and the native setInterval method? Moreover, why does it matter for these, but not for the normal addEventListener?
Example with onComplete events (assuming blinkOn() is called):
//like this the onComplete event works normally and the functions call eachother
function blinkOn() { $blink.fadeIn( 500, blinkOff ); }
function blinkOff() { $blink.fadeOut( 500, blinkOn ); }
//like this blinkOff won't be called after the fadeIn
function blinkOn() { $blink.fadeIn( 500, blinkOff ); }
var blinkOff = function() { $blink.fadeOut( 500, blinkOn ); };
Example with setInterval:
//works fine
var timer = setInterval( onTimer, 700);
function onTimer() { ... }
//won't work
var timer = setInterval( onTimer, 700);
var onTimer = function() { ... }
The reason I’d like to know is because I want consistency in my code. If the only way to get that is just using function a() { ... }, that’s okay. But I think var a = function() { ... } is more clear in defining scope. And I’m just really curious.
If you were to define your function above where your calls to the function are, you’d have no issues.
var toggleLight = function () { light = !light; };
setInterval(toggleLight, 500);
Your problem is that you’re trying to access things which don’t exist yet.
It’s the exact same thing as trying to do this:
When the program hits
c,aandbdon’t exist.Think of this as happening in three steps, for every single function:
STEP 1.
The engine grabs the named function
addand works out what it does (defines all named-functions first).STEP 2.
The engine locates all variables in the function and sets them to
undefined:STEP 3.
The engine initializes all variables in order.
So doing something like this:
Is equal to this:
Solution:
Separate your implementation from your action.
Make sure everything is defined before you call anything.