views:

75

answers:

2

I am currently logging an AJAX application with messages which include the times of certain interactions. So I have a couple of places where the code follows a pattern such as this:

var startTime = new Date();
this.doFunction();
var endTime = new Date();
logger.log("doFunction took " + (endTime - startTime) + " milliseconds.");

What I'm look to do is separate the timing into one library function, which takes a function as a parameter, to look something like:

time : function(toTime) {
    var startTime = new Date();
    eval(toTime);
    var endTime = new Date();
    logger.log(toTime + " took " + (endTime - startTime) + " milliseconds.");
}

(Syntax may be wrong, I'm not too familiar with JavaScript)

So that then instead of doing the timing I would just do:

time(this.doFunction);

My question is, do different browsers have different behaviour when it comes to eval()? Such as firing off the eval into a new thread, thus rendering my timing incorrect?

Any other advice on timing would be appreciated.

+1  A: 

No. All browsers are single-threaded in the javascript engine. I suspect that you can also solve this problem simply by invoking toTime() as a function instead of using eval(). You may want to look into the javascript arguments object and the javascript "call" and "apply" methods to transparently forward the arguments passed to your outer "time" function to the inner "toTime" function.

krosenvold
A: 

Eval should be synchronous.

You shouldn't use eval() but toTime.call(), because you should avoid using eval.

Georg
Why is it that I should avoid using eval()? I don't think I will, but I'm just curious..
Grundlefleck
Because eval() can make it easy for other people to insert malicious javascript and in most cases one does not need to use eval().
Georg
Ah, never considered that. Cheers.
Grundlefleck