Reputation: 4141
I get "undefined is not a function" when trying to run this. What am I missing?
function bench(func) {
var start = new Date.getTime();
for(var i = 0; i < 10000; i++) {
func();
}
console.log(func, new Date.getTime() - start);
}
function forLoop() {
var counter = 0;
for(var i = 0; i < 10; i++) {
counter += 1;
}
return counter;
}
bench(forLoop);
Upvotes: 2
Views: 8847
Reputation: 707456
You need to use:
new Date().getTime();
instead of
new Date.getTime();
Here's some explanation of what was doing on. When you do:
new Date.getTime();
it looks for the getTime()
property on the Date
constructor and that is undefined
because that property exists on the prototype or actual instantiated objects, not on the constructor itself. Then it tries to do new undefined
which obviously doesn't work and gives you the error you saw.
When you do:
new Date().getTime();
It is essentially doing this:
(new Date()).getTime();
because of operator precedence and that is what you want. It will create a new Date()
object and then call the .getTime()
method on it.
Upvotes: 6
Reputation: 4457
You need to instantiate the Date object before invoking methods on it.
Example:
var date = new Date()
start = date.getTime();
Upvotes: 1