maxhallinan maxhallinan - 7 months ago 18
Javascript Question

setTimeout passed named function vs. anonymous function

On the MDN page for

I find this example where a named function is passed to window.setTimeout:

var timeoutID;

function delayedAlert() {
timeoutID = window.setTimeout(slowAlert, 2000);
}

function slowAlert() {
alert("That was really slow!");
}

function clearAlert() {
window.clearTimeout(timeoutID);
}


In code I am maintaining, I have encountered the equivalent of this example where an anonymous function is declared as it is passed to
window.setTimeout
:

var timeoutID;

function delayedAlert() {
timeoutID = window.setTimeout(function(){
alert("That was really slow!");
}, 2000);
}

function clearAlert() {
window.clearTimeout(timeoutID);
}


Is there an important difference between these two ways of delaying the alert? I trust MDN more than the code I'm working with, so I want to understand why MDN phrased their example using a separate function declaration.

edit: Thank you @TravisJ @jfriend00 @PlatinumAzure for the clear and helpful answers.

Answer

There is not really much of a difference if it isn't being done much. The anonymous function is going to use some insignificantly more amount of memory than the separate function.

The reason is that the separate function declaration is going to be used essentially as a pointer so it may be re-used. However, the anonymous function is going to need to be constructed every time. It is a very small difference.

The basic difference is going to be scoping and parameters. You cannot pass parameters to a function pointer. Does the function inside of the timeout need to share scope with its parent? If so, then an anonymous function may be more worthwhile than a declared function in another scope. A common one is to pass in this.

var that = this;
window.setTimeout(function(){
 //keep in mind this anonymous function's `this` will be window
 showAlert(that.message);
},2000;

In order to pass a message, for example if your alert was function showAlert(msg) then you would need to use an anonymous function window.setTimeout(function(){showAlert("hello");}, 2000);.

What you really want to avoid using is a string there. Such as

window.setTimeout("slowAlert()", 2000);

This is considered bad practice because a Function will be constructed based off of the string similar to using eval.