DEV Community

Cover image for The browser console has a count method
Christian Heilmann
Christian Heilmann

Posted on • Originally published at christianheilmann.com

7 2

The browser console has a count method

When debugging or analysing JavaScript, you often see people trying to find out how often a certain function is called. The common way to do that is to use a global counter variable to increment and log in the function.

var i = 0;
function test(){
  // other functionality
  i++;
  console.log(i);
  // other functionality
}
Enter fullscreen mode Exit fullscreen mode

There is, however, a better method. The Console of the browser has a count() and countReset() method that event takes a label. That means you can avoid the global.

function bettertest(){
  console.count('bettertest');
}
Enter fullscreen mode Exit fullscreen mode

You can see it in action in this screencast.

Screencast of the two ways to count how often a method was called in comparison

This is part of the standard Console API and should be supported in all browsers.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
nickytonline profile image
Nick Taylor

TIL!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay