Reputation: 4755
I'm attempting to create a module where I can implement a timer (Parse Cloud Code). The problem is it's returning a null value for the final execution time. I presume it has to do with not being able to retrieve the initial start variable.
How can I make that happen. Thanks!
var start;
var end;
exports.beginTimer = function beginTimer(functionName) {
//Start timing now
var start = new Date().getTime();
}
exports.endTimer = function endTimer(functionName) {
//End timer
var end = new Date().getTime();
var time = end - start;
alert('Execution time for' + functionName + ': ' + time);
}
Upvotes: 0
Views: 201
Reputation: 1993
By using the keyword "var" in your method you create this variable in the namespace of the method itself.
Thats why in your "beginTimer" method your variable is already deleted at the end of the method block. So the easiest way to make your code work is to remove "var" from the variable declaration in your methods.
This will maybe occur new errors if you call multiple methods before finishing them because they will all use the same "start" and "end". You might want to think about using some kind of mapping between "functionName" and "start".
You could do this for example:
var start = {};
exports.beginTimer = function beginTimer(functionName) {
//Start timing now
start[functionName] = new Date().getTime();
}
exports.endTimer = function endTimer(functionName) {
//End timer
var end = new Date().getTime();
var time = end - start[functionName];
alert('Execution time for' + functionName + ': ' + time);
}
Since this could occur new problems when a method gets called twice before it already finished you might want to work with a unique identifier you pass to the method.
var start = {};
exports.beginTimer = function beginTimer(functionName, uid) {
//Start timing now
start[uid] = new Date().getTime();
}
exports.endTimer = function endTimer(functionName, uid) {
//End timer
var end = new Date().getTime();
var time = end - start[uid];
alert('Execution time for' + functionName + ': ' + time);
}
You would have to generate this UID in your method.
Upvotes: 1
Reputation: 943996
You've redeclared start
and end
within each function.
This masks the global variables with local variables of the same name.
endTimer
gets undefined
as the value of start
.
Don't use var
unless you want to create a locally scoped variable.
Upvotes: 3