Notes of Maks Nemisj

Experiments with JavaScript

Detecting browser’s activity within JavaScript

Experiment, test, analyze. Experiment again, test again, analyze again. This is the process of learning the environment, the language and the tools I work with. Taking things apart, looking inside, diving deeper and building a picture of understanding. I think JS is a language with a lot of hidden corners and this time I’ve decided to dig into timers and intervals of the JavaScript. This experiment grew into a browser-based activity monitor of JavaScript execution and I would like to share my experience about it, with you.

How it all started

As you all know, timers in JavaScript get triggered at the moment when the browser is idling. This is described very well in one of the John’s articles at http://ejohn.org/blog/how-javascript-timers-work/ : “Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there’s been an opening in the execution.”

This information gave me a pretty absurd idea: Is it possible to determine the active/idle state of the browser by using the “opening” behavior of the timers? I thought – yes. But the question is – how? If we start looping “setTimeout” with scheduled time of zero milliseconds, we could collect an interval between the timers and identify the current browser’s state ( active/idling ) based on the interval’s info. Something, like the picture below shows:

timeout works

To prove for myself that this craziness had at least a small rational kernel, I built a small prototype. I injected it into a heavy ajax-based application and I was quite happy with the results. All the results I received had a common pattern in them, indicating that the calculated interval is a reliable source for tracking the browser’s activity. I do agree, that maybe this approach can’t be used for precise profiling of an application, but I still think that it could be used to get the global picture of the browser’s execution flow for the ajax driven applications.

Path into the experiment

To quickly proceed with this experiment, I started with pretty simple code. Collect the difference between the current time and time of the previous timer call, save all the values into an array, and I have everything I need for now. In the first place the code looked like this:

function start(){
    var timer_start = (+new Date()),
          timer_end,
          stack = [];

    (function collect() {
        timer_end = (+new Date());
        stack.push( timer_end - timer_start );
        timer_start = timer_end;
        setTimeout( collect, 0 );
    })();

    return stack;
}

// Example of the stack array
// [ 10, 11, 10, 11, 10, 11, 14, 19, 17, 16, 15,
//    15, 13, 13, 13, 12, 17, 13, 10, 10, 11, 10,
//    11, 10, 11, ...]

In all the tests I’ve done so far, there was one thing bothering me. Even when the browser was idling, there were almost no zero values in an array, but two digits were continuously repeating. For example: in Firefox (mac) these were 10 and 11. You can see that also also in the example above.

It was clear to me that these two values represent a kind of “baseline” for browser’s idling state. In Mozilla Developer Network (MDN) it’s described as a timeout clamping https://developer.mozilla.org/en/DOM/window.setTimeout ( at the bottom of the page ). Summarizing: clamping is the minimum amount of time between any interval or timer. I also tested different browsers in diferent OS’s ( Windows, Linux, OSX ) and almost none of them got zero values at the moment of idling. Besides that, these clamping values varied between all the browsers.

The funny thing about the timers clamping is that this interval is not just one static number, but two numbers, repeating in turn. These two numbers I called the “baseline”. Let’s look at some of them in different browsers.

Browser “Baseline”
Firefox 3.5.11 ( osx ) 10, 11
Safari 5.0 ( osx ) 10, 11
Chrome 5.0.375 ( osx, win ) 4, 5
IE 7.0 ( win ) 15, 16
Opera ( win ) 10, 11

Table: the baseline for different browsers

Despite the fact that the MDN claims that there is always a delay between timers, this was not the case. Sometimes the interval values were lower than the clamping interval, even dropping to zero value. Digging deeper sheds some light on this weird behavior. I’ve discovered that the dropped interval happened only at the moments of non idle state, when the browser was busy with really heavy execution flow. This gave me an idea that the timers are executing in two different cases.

Case one: The browser is idling. It periodically checks for the suitable timer/interval inside the timer’s and interval’s queue. This period is exactly the clamping moment, which is described in the MDN. At the moment when the browser finds an interval or a timer to be executed – fire.

Case two: Browser is executing JS code. Periodic checks are stopped to prevent timers and intervals being executed at the moment of other code execution. This means, the browser is waiting for an “opening” now. When the execution is finished, the browser starts checking the timers’ queue, without waiting for clamping offset. It controls if the execution of the timer was not far away in the past/future from the current moment and if not the browser executes it. This case also explains why my prototype code gave as a first value – zero. Because there was nothing else to execute and browser could pick up the scheduled timeout.

I do not claim, that this is actually what is happening, but by analyzing from the outside, it appeared to me so.

Tests with simple dump tool

Well, enough of raw data. Users need a GUI and I also needed some representation of the collected data. For this reason I made a first prototype version of a dumping tool. As an input it receives the array with values and as an output it produces some “very” simple graph like the one bellow.

dump rendering

This graph has two sates: “activity” and “no activity” state. They are represented by high level and low level of the bar, respectively. As you’ve noticed the high bar consists of red and black areas. In this way duration and type of the activity was represented.

Let’s start with the red part. The longer the red bar is, the longer the browser stays active. It becomes red, only when the activity interval is longer than the “baseline”. At the moment when the activity goes below the baseline, it becomes a small black stripe.

Because of the visual graph, you can analyze data much faster than with the raw array. Faster analysis, more intensive tests. More conclusions. And the first conclusion which I made was that, it is almost impossible to trace activity, if it is less than the clumping interval. But still, here comes the nice part, web pages nowadays are all heavily event driven, and even a small event often executes longer than the clumping interval. Take for example a typing event, resizing a window, etc. Typing event in an text-area triggered this so well, that I could easily see this in the graph.

Firefox typing

Image : Firefox Typing activity

chrome typing

Image : Chrome Typing activity

Or, scrolling. I scrolled a couple of times and I think, this is quite fascinating to see, that graph shows you this four scrolls I made.

safari scrolling

Image : Safari scroll activity

Last activity as an example is based on resizing of the Firefox window:

firefox resize

Image : Firefox resize activity

Another conclusion I made was that based on the examples you can see that the timers depend not only on the JavaScript execution of the code, but also on the internal parts of the browser, like moving of the window, or opening a new tab. So, keep this in mind 🙂

Besides all the graphs of event driven behavior, I also came across another interesting aspect in Firefox when it was “doing nothing” and checking the idle state. Firefox when idling still has some activity peeks. I also looked at Chrome and Safari, but they are all stable as statues. These browsers showed no sign of activity at all, in idle state. First, I thought that it’s just some crazy late running timer, but when I checked the Activity Monitor of OSX I found that there are also the same small peaks of the CPU usage for Firefox processor.

firefox peeks activity

Image : Firefox small idle peaks

From here, I can draw two conclusions: 1. Firefox is really doing something all the time (which is reflected in the CPU usage) or 2. Firefox just has inaccurate timers.

More ?

I could not resist and not to build some kind of runtime activity monitor.

First thing which I did was to check the response of this monitor to the activity. The fastest way was to fire up native Activity Monitor of OSX and compare the peaks of both. It was a surprise to see peaks in the browser monitor first, and only after that in OSX. 🙂

firefox activity mini

Image : Firefox and Activity Monitor

Because runtime monitor gives you a global overview of the activity, it was really nice to play with it in a different browsers and compare how they react on different kinds of events/execution. It gave me an instant coverage of the places where browsers spend much time and of the places where they “fly”. For example, I used the test code like this

var arr = [];
for (var i=0;i<16099;i++) {
    var div = document.createElement("div");
    arr.push( div );
}

and I got these results :

firfox execution
image: Firefox (win)

ie execution
image: IE6

chrome execution
image: Chrome (win)

Another thing which I noted is the way IE behaves. Its activity always stays at “zero” level when it’s idle, a really “silent” browser. Also in the image above you can see that IE gave only the activity of the JS execution, but nothing else. I assume that it has to do with the clamping interval. It has the highest interval between all the browsers, which means that the activity bellow 15ms will always stays invisible to us. Sad. At least we can track resize of the window, with ease 🙂

ie resize

Image: Resizing IE

The source you can find at github.

Epilogue

While I was busy with timers I found another interesting article about timers and intervals. I did a small experiment with that too and it appeared that the argument which Firefox passes to the timeout function is equal to the sum of the calculated interval + the baseline. It’s not always the same, but in most situations it is. I did not perform any further tests in other browsers, but if you are interested feel free to fill this gap.

This experiment gave me some interesting thoughts. This monitor can actually help you to look at the application from a different angle. It can show you the way the application performs and interacts with the browser. It can show you that the clicking on a button in one browser triggers a more complicated wave of the execution than in the other browsers. It helps to see you your web application as a whole piece and not as a bunch of separated code regions.

As usually, a playground is available for everyone who is interested in it :

http://nemisj.com/src/amonjs/

Known issues: In Linux in Firefox calibration of the baseline sometimes is not working the first time, so you should recalibrate if it behaves strangely.

, , ,

3 thoughts on “Detecting browser’s activity within JavaScript

  • Paul Sayre says:

    Another thing you might look into is the minimum timeouts set by the browsers. For instance, HTML5 says the min is 4ms. If you use a timeout of 10ms, you’ll see almost all browsers hitting the same mark every time. Might try running your benchmarks with a that timeout.

    Another good reason to use 10ms is you can then preempt your regular timeouts using a timeout of 0ms.

    Lastly, if you have access to different operating systems, it might be interesting to compare same browsers on different OSs. Since the timeout uses the OS time, then the result.

    Just some food for thought.

  • Alexander Nestorov says:

    Great work! 🙂

    I just tested this in Chrome 24 and it’s working right as expected. Anyways, there is something that called my attention. If you start the monitor and then switch to another tab, wait for a few seconds (10-15) and then switch back to the tab on the monitor, you’ll see that the activity was 100% while you were looking at the other tab (even if you haven’t touched/moved/scrolled anything).

  • Maks Nemisj says:

    My assumption is that chrome could stop timers when the tab is not visible, but i haven’t tested it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.