im trying to get the current time timeNow in javascript and at the end of the script get
timeEnd which is when the script finished executing for example:
newDate = new Date();
timeNow = newDate.getTime();
for(i=0; i < 5; i ++){
console.log("printing" + i);
}
timeEnd = timeNow - newDate.getTime();
console.log(timeEnd);
i want to get the time it took to excute this script in seconds or milliseconds, but the result is 0. i don’t see why, can you help me thanks.
The
Dateobject does not keep ticking once it’s constructed, it only represents a single instant in time.You need to re-evaluate the time at the end of the script and then compare that value with the first one.
Note that on modern ES5 browsers you can use the “static”
Date.now()function to get the current time. This is less expensive that constructing a whole newDateobject. On older browsers you can emulate this function with this shim:At which point the required code becomes:
FWIW, your simple loop reports 2ms when run on the Chrome console on my laptop.