0

I'm currently a teacher's assistant in a web development course. Today, a student asked for help with his homework, in which he'd used setInterval, passing as the first parameter a function which he didn't define until a few lines of code later. I told him that wouldn't work, as the function would be undefined by the time the interval setting code was reached.

To my surprise, it worked perfectly. I've been trying to research this and am coming up blank: does JavaScript actually wait until the first execution of the callback to even see if the function name passed to it exists? That seems so counter-intuitive, but I can't imagine any other reason it would have worked. Where can I find out more about this unexpected behavior?

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26

1 Answers1

1

It depends: If its a function expression :

//callback not defined ( exists but undefined)
var callback=function(){};
//callback defined

If its a function declaration :

//callback is defined
function callback(){}
//callback is defined

This is called hoisting, so vars and functions are moved to the top.


It also depends on the passed function too:

setInterval(callback,0);//doesnt work, callback is *undefined* in this moment

setInterval(function(){ callback();},100);//does work as callback is just called before being referenced.
var callback=function(){};
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151