Why does setTimeout with a new function ignore the wait interval?

When trying to do this:

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

I accidentally wrote this:

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

The first version waits for 500 milliseconds, then an alert. The latter warns immediately.

Why does adding a new before a function cause this behavior?

+4
source share
3 answers

Using new creates a new object using an anonymous function as its constructor, so your function starts and warns immediately.

+5
source

The latter creates an instance of Object and immediately calls its constructor.

+2
source
 new function(){alert("Boo");} 

is equivalent

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

the second line, as you can see, calls your function using temp1 as the constructor.

0
source

All Articles