Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / test / data / third_party / spaceport / js / util / benchAsync.js
blobe821557938fd026076f6fc27dc787e70a88b71bf
1 define([ 'util/ensureCallback' ], function (ensureCallback) {
2     var requestAnimationFrame
3          = window.requestAnimationFrame
4         || window.webkitRequestAnimationFrame
5         || window.mozRequestAnimationFrame
6         || window.oRequestAnimationFrame
7         || window.msRequestAnimationFrame;
9     // Benchmarks fn until maxTime ms has passed.  Returns an object:
10     //
11     // {
12     //   "score" -- approximate number of operations performed in that time ('score')
13     // }
14     function benchAsync(maxTime, fn, callback) {
15         if (typeof fn !== 'function') {
16             throw new TypeError('Argument must be a function');
17         }
19         var startTime;
20         var running = true;
21         
22         function checkDone(endTime) {
23             if (!running) {
24                 return;
25             }
27             if (endTime - startTime >= maxTime) {
28                 running = false;
30                 var elapsed = endTime - startTime;
31                 var timeoutScore = timeoutTimes.length / elapsed * maxTime;
32                 var rafScore = rafTimes.length / elapsed * maxTime;
33                 return callback(null, {
34                     startTime: startTime,
35                     timeoutScore: timeoutScore,
36                     rafScore: rafScore,
37                     score: requestAnimationFrame ? rafScore : timeoutScore,
38                     elapsed: elapsed
39                 });
40             }
41         }
43         function rafUpdate() {
44             var now = Date.now();
45             rafTimes.push(now);
46             checkDone(now);
47             if (running) {
48                 requestAnimationFrame(rafUpdate);
49             }
50         }
51         
52         var timeoutTimes = [ ];
53         var rafTimes = [ ];
54         
55         function next() {
56             fn(timeoutTimes.length, function () {
57                 var now = Date.now();
58                 timeoutTimes.push(now);
59                 checkDone(now);
60                 if (running) {
61                     next();
62                 }
63             });
64         }
66         setTimeout(function () {
67             startTime = Date.now();
69             if (requestAnimationFrame) {
70                 requestAnimationFrame(rafUpdate);
71             }
73             next();
74         }, 0);
75     }
77     return benchAsync;
78 });