ripper234
ripper234

Reputation: 230156

Why does setTimeout with new function ignore wait interval?

When trying to do this:

setTimeout(function(){alert("Boo");}, 500);

I accidentally wrote this:

setTimeout(new function(){alert("Boo");}, 500);

The former version waits 500 millis, then alerts. The latter alerts immediately.

Why does adding new in front of the function cause this behavior?

Upvotes: 4

Views: 517

Answers (3)

c-smile
c-smile

Reputation: 27470

new function(){alert("Boo");} 

is an equivalent of

var temp1 = function(){alert("Boo");};
var temp2 = new temp1();

second line as you see invokes your function using temp1 as a constructor.

Upvotes: 0

Digital Plane
Digital Plane

Reputation: 38264

Using new creates a new object using the anonymous function as its constructor, so your function runs and alerts immediately.

Upvotes: 5

alex
alex

Reputation: 490403

The latter one instantiates an Object and calls its constructor immediately.

Upvotes: 2

Related Questions