test.html 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta
  6. name="viewport"
  7. content="width=device-width, initial-scale=1.0"
  8. />
  9. <title>Document</title>
  10. </head>
  11. <body>
  12. <script>
  13. /**
  14. * @param {number} targetCount 不小于1的整数,表示经过targetCount帧之后返回结果
  15. * @return {Promise<number>}
  16. */
  17. const getScreenFps = (() => {
  18. // 先做一下兼容性处理
  19. const nextFrame =
  20. window.requestAnimationFrame ||
  21. window.webkitRequestAnimationFrame ||
  22. window.mozRequestAnimationFrame;
  23. if (!nextFrame) {
  24. console.error('requestAnimationFrame is not supported!');
  25. return;
  26. }
  27. return (targetCount = 120) => {
  28. // 判断参数是否合规
  29. if (targetCount < 1)
  30. throw new Error('targetCount cannot be less than 1.');
  31. const beginDate = Date.now();
  32. let count = 0;
  33. return new Promise((resolve) => {
  34. (function log() {
  35. nextFrame(() => {
  36. if (++count >= targetCount) {
  37. const diffDate = Date.now() - beginDate;
  38. const fps = (count / diffDate) * 1000;
  39. return resolve(fps);
  40. }
  41. log();
  42. });
  43. })();
  44. });
  45. };
  46. })();
  47. getScreenFps().then((res) => {
  48. console.log(res);
  49. });
  50. </script>
  51. </body>
  52. </html>