Monitoring Function Calls
Greetings, friends! In this tutorial, I'd like to discuss the monitor utility function that is built into the Google Chrome browser. This function is part of the Console Utilities API.
To begin, open up the Chrome DevTools console using the keyboard shortcut Option + Command + J
on a Mac or Ctrl + Shift + J
on Windows. Then, paste the following code into the console.
function sum(x, y) {
return x + y;
}
monitor(sum);
sum(1, 2);
By calling the monitor
function on sum
, we create a monitor that will watch for the sum
function to be called. Every time sum
is invoked, a message is logged to the console. This message includes the name of the function, and the parameters that were passed into that function.
function sum called with arguments: 1, 2
However, the monitor
function will not display the parameters passed into arrow functions as of the time of writing.
const multiply = (x, y) => {
return x * y;
}
monitor(multiply);
multiply(1, 2);
You will likely see the following message logged to the console. The parameters are now missing!
function multiply called
At least we still get notified that the function was called! If we want to stop monitoring a function, then we can either refresh the page or use the unmonitor function.
function sum(x, y) {
return x + y;
}
monitor(sum);
sum(1, 2);
unmonitor(sum);
sum(1, 2);
After calling the unmonitor
function, the sum
function will no longer be monitored. Although it would probably be better to stick with the debugger built into DevTools, the monitor
function can be handy in certain circumstances.