Kyoko Sasagava
Kyoko Sasagava

Reputation: 121

How many times can you make count += 1 in one second with Javascript?

I am trying to measure how many times i can make "count = count + 1" in one second. But this function breaks browser. Anyone can say why is it happening or have a better method to calculate it?

function counter(){
   var count = 0;
   var trs = true;
   while(trs){
      count = count + 1;
      setTimeout(() => {trs = false;}, 1000);
   }
   console.log(count);
}

Upvotes: 4

Views: 681

Answers (2)

Armin Primadi
Armin Primadi

Reputation: 774

The reason it crashes is because of infinite loop. JavaScript is event driven + single threaded and in JavaScript execution model, the function must finish before it yields control to another function. Thus, the code while (trs) {...} never yields control to the function defined in setTimeout because it never finishes. trs is always true.

Nice visualization on how the JavaScript execution model works: https://blog.avenuecode.com/understanding-the-javascript-concurrency-model

Here's a better way to do it:

function counter() {
  var count = 0
  var start = Date.now()
  var end = start + 1000
  while (Date.now() <= end) {
    count = count + 1
  }
  console.log(count)
}

Upvotes: 4

SomoKRoceS
SomoKRoceS

Reputation: 3053

There is an infinite loop over there. Now, since javascript is single-threaded, the browser will get stuck performing that infinite loop, which may cause the cache filling up very quickly and cause a crash (or not re-render anything).

First, generally speaking, it is better to create the setTimeout only once, before you call while:

   var count = 0;
   var trs = true;
   setTimeout(() => {trs = false;}, 1000);
   while(trs){
      count = count + 1;
   }
   console.log(count);

However, this will also cause a crash.

You can try to measure the operations differently, measure how much time it takes for a single count = count + 1 operation to run, then find how many of these can be executed in a second (Although it is not the same as running X consecutive operations, which another parameters could influence the result, but I am assuming you care about a single operation or single function you want to measure).

   var count = 0;
   var t0 = performance.now()
   count = count + 1;
   var t1 = performance.now()
   console.log(1000/(t1 - t0));

If you want it to be inside a loop, you can also include the value check (with if), which the while does before executing its block.

   var count = 0;
   var trs=true;
   var t0 = performance.now()
   if(trs==true){
      count = count + 1;
   }
   var t1 = performance.now()
   console.log(1000/(t1 - t0));

Upvotes: 2

Related Questions