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);
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);
Share
Improve this question
edited May 5, 2014 at 21:18
cookie monster
11k4 gold badges33 silver badges45 bronze badges
asked May 5, 2014 at 20:44
meadowstreammeadowstream
4,1512 gold badges22 silver badges24 bronze badges
3
- On which line do you get that error? – jfriend00 Commented May 5, 2014 at 20:46
- 1 possible duplicate of javascript Date().getTime() is not a function – isherwood Commented May 5, 2014 at 20:47
-
2
@isherwood - this doesn't look like a dup of that one. The solution in that case was to add use
new Date()
instead of justDate()
. The OP here was already usingnew
. – jfriend00 Commented May 5, 2014 at 20:50
2 Answers
Reset to default 6You 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.
You need to instantiate the Date object before invoking methods on it.
Example:
var date = new Date()
start = date.getTime();
http://jsfiddle/3TJLq/