1

I was messing around with JavaScript, and I wanted to do something I have never done before.

I looked up various things online, wondering how fast a function calls.

I found this code:

var performance = window.performance;
var t0 = performance.now();
doWork();
var t1 = performance.now();
console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")

I personally loved this code, because it runs the function automatically, and it is easy to set up because all you have to do is change doWork(); to your function, and put the code under the function.

I did something where I logged "Hi" to the console, from a function and got many different times for the function to be running.

Almost like human reaction times, each time it calls the function, a variable amount of time is required to run the function.

It is completely random, and it is running the same function over and over again. Here is my full JavaScript code:

function hi() {
  console.log("Hi")
}
var performance = window.performance;
var t0 = performance.now();
hi();
var t1 = performance.now();
console.log("Call to function took " + (t1 - t0) + " milliseconds.")

Can anyone explain why it calls at completely different times?

1
  • Just to be clear, I am using JSfiddle. Commented Feb 12, 2021 at 5:01

1 Answer 1

1

Sub-millisecond timers can't be relied on to be accurate in JS, especially for such tiny codes like a single console.log. As MDN says:

It's important to keep in mind that to mitigate potential security threats such as Spectre, browsers typically round the returned value by some amount in order to be less predictable. This inherently introduces a degree of inaccuracy by limiting the resolution or precision of the timer. For example, Firefox rounds the returned time to 1 millisecond increments.

If they were completely accurate, and as precise as possible, it could theoretically be a security risk.

There may be other reasons for the same action to take a different amount of time too, such as the amount of resources being used by other parts of the system (other programs, other tabs, etc).

Sign up to request clarification or add additional context in comments.

1 Comment

Oh well that would explain why. I have 64 tabs open. Almost all of them are just programming.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.