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?

1
  • 1
    Function definitions are hoisted... Commented Jun 21, 2017 at 7:55

1 Answer 1

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(){};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.