A simple code to display the FPS of the current page

When writing the front-end code, especially when making a front-end framework, it is often necessary to know the general performance of the code in time. At this time, if there is a good way to see the fps of the current page all the time, it is good.

The overall idea is to record the current time as the last time to record fps. The fsp counter is continuously accumulated through the request animationframe callback, and whether the last time to record fps is more than 1000ms is judged. If the conditions are met, the fps accumulator value is displayed as the current fps, and the fps accumulator is reset.

Here is a simple code to display FPS:

 1 var showFPS = (function () {
 2     // noinspection JSUnresolvedVariable, SpellCheckingInspection
 3     var requestAnimationFrame =
 4         window.requestAnimationFrame || //Chromium  
 5         window.webkitRequestAnimationFrame || //Webkit 
 6         window.mozRequestAnimationFrame || //Mozilla Geko 
 7         window.oRequestAnimationFrame || //Opera Presto 
 8         window.msRequestAnimationFrame || //IE Trident? 
 9         function (callback) { //Fallback function 
10             window.setTimeout(callback, 1000 / 60);
11         };
12 
13     var dialog;
14     var container;
15 
16     var fps = 0;
17     var lastTime = Date.now();
18 
19     function setStyle(el, styles) {
20         for (var key in styles) {
21             el.style[key] = styles[key];
22         }
23     }
24 
25     function init() {
26         dialog = document.createElement('dialog');
27         setStyle(dialog, {
28             display: 'block',
29             border: 'none',
30             backgroundColor: 'rgba(0, 0, 0, 0.6)',
31             margin: 0,
32             padding: '4px',
33             position: 'fixed',
34             top: 0,
35             right: 'auto,',
36             bottom: 'auto',
37             left: 0,
38             color: '#fff',
39             fontSize: '12px',
40             textAlign: 'center',
41             borderRadius: '0 0 4px 0'
42         });
43         container.appendChild(dialog);
44     }
45 
46     function calcFPS() {
47         offset = Date.now() - lastTime;
48         fps += 1;
49 
50         if (offset >= 1000) {
51             lastTime += offset;
52             displayFPS(fps);
53             fps = 0;
54         }
55 
56         requestAnimationFrame(calcFPS);
57     };
58 
59     function displayFPS(fps) {
60         var fpsStr = fps + ' FPS';
61 
62         if (!dialog) {
63             init();
64         }
65 
66         if (fpsStr !== dialog.textContent) {
67             dialog.textContent = fpsStr;
68         }
69     }
70 
71     return function (parent) {
72         container = parent;
73         calcFPS();
74     };
75 })();
76 
77 showFPS(document.body);

Tags: Javascript IE

Posted on Tue, 03 Dec 2019 22:52:58 -0800 by spoco