YouTube CPU Tamer by AnimationFrame

Reduce Browser's Energy Impact for playing YouTube Video

Fra 27.08.2023. Se den seneste versjonen.

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2021-2023 CY Fung
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24.  
  25. */
  26. // ==UserScript==
  27. // @name YouTube CPU Tamer by AnimationFrame
  28. // @name:ja YouTube CPU Tamer by AnimationFrame
  29. // @name:zh-TW YouTube CPU Tamer by AnimationFrame
  30. // @namespace http://tampermonkey.net/
  31. // @version 2023.08.27.0
  32. // @license MIT License
  33. // @author CY Fung
  34. // @match https://www.youtube.com/*
  35. // @match https://www.youtube.com/embed/*
  36. // @match https://www.youtube-nocookie.com/embed/*
  37. // @match https://www.youtube.com/live_chat*
  38. // @match https://www.youtube.com/live_chat_replay*
  39. // @match https://music.youtube.com/*
  40. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  41. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/youtube-cpu-tamper-by-animationframe.webp
  42. // @supportURL https://github.com/cyfung1031/userscript-supports
  43. // @run-at document-start
  44. // @grant none
  45. // @unwrap
  46. // @allFrames true
  47. // @inject-into page
  48.  
  49. // @description Reduce Browser's Energy Impact for playing YouTube Video
  50. // @description:en Reduce Browser's Energy Impact for playing YouTube Video
  51. // @description:ja YouTubeビデオのエネルギーインパクトを減らす
  52. // @description:zh-TW 減少YouTube影片所致的能源消耗
  53. // @description:zh-CN 减少YouTube影片所致的能源消耗
  54.  
  55. // @description:ko YouTube 비디오 재생 시 브라우저의 에너지 영향을 줄입니다.
  56. // @description:ru Снижает энергетическое воздействие браузера при воспроизведении видео на YouTube.
  57. // @description:af Verminder die energie-impak van die blaaier vir YouTube-video speel
  58. // @description:az YouTube videolarını oynamaq üçün Brauzer enerji təsirini azaldır
  59. // @description:id Kurangi Dampak Energi Browser untuk memutar Video YouTube
  60. // @description:ms Kurangkan Impak Tenaga Pelayar untuk memainkan Video YouTube
  61. // @description:bs Smanji energetski uticaj preglednika za reprodukciju YouTube videa
  62. // @description:ca Redueix l'impacte energètic del navegador per reproduir vídeos de YouTube
  63. // @description:cs Snížit energetický dopad prohlížeče při přehrávání videí na YouTube
  64. // @description:da Reducer browserens energipåvirkning for at afspille YouTube-video
  65. // @description:de Reduzieren Sie die Energieauswirkungen des Browsers für die Wiedergabe von YouTube-Videos
  66. // @description:et Vähendage YouTube'i video esitamiseks brauseri energiamõju
  67. // @description:es Reduzca el impacto energético del navegador al reproducir videos de YouTube
  68. // @description:eu Gutxitu nabigatzeko energiaren eragina YouTube bideoak erreproduzitzeko
  69. // @description:fr Réduire l'impact énergétique du navigateur lors de la lecture de vidéos YouTube
  70. // @description:gl Reduzca o impacto enerxético do navegador para reproducir vídeos de YouTube
  71. // @description:hr Smanjite energetski utjecaj preglednika za reprodukciju YouTube videa
  72. // @description:zu Qaqalitsha Umbono We-Energy we-Browser ukuze udlale i-Video ye-YouTube
  73. // @description:is Minkaðu orkuáhrif vafra til að spila YouTube myndband
  74. // @description:it Riduci l'impatto energetico del browser per la riproduzione di video di YouTube
  75. // @description:sw Punguza Athari ya Nishati ya Kivinjari kwa kucheza Video za YouTube
  76. // @description:lv Samaziniet pārlūkprogrammas enerģijas ietekmi YouTube video atskaņošanai
  77. // @description:lt Sumažinkite naršyklės energijos poveikį žaidžiant „YouTube“ vaizdo įrašus
  78. // @description:hu Csökkentse a böngésző energiaterhelését a YouTube videó lejátszásához
  79. // @description:nl Verminder de energie-impact van de browser bij het afspelen van YouTube-video's
  80. // @description:uz YouTube videoni tinglash uchun brauzer energiyasi ta'sirini kamaytirish
  81. // @description:pl Zmniejsz zużycie energii przeglądarki podczas odtwarzania filmów na YouTube
  82. // @description:pt Reduza o Impacto Energético do Navegador ao reproduzir Vídeos do YouTube
  83. // @description:pt-BR Reduza o Impacto Energético do Navegador ao reproduzir Vídeos do YouTube
  84. // @description:ro Reduceți impactul energetic al browser-ului pentru redarea videoclipurilor YouTube
  85. // @description:sq Zvogëlo ndikimin e energjisë të shfletuesit për luajtjen e video YouTube
  86. // @description:sk Znížte energetický dopad prehliadača pri prehrávaní videí na YouTube
  87. // @description:sl Zmanjšajte energijski vpliv brskalnika pri predvajanju videoposnetkov YouTube
  88. // @description:sr Smanjite energetski uticaj pregledača za reprodukciju YouTube videa
  89. // @description:fi Vähennä selaimen energiankulutusta YouTube-videoiden toistossa
  90. // @description:sv Minska webbläsarens energipåverkan för att spela YouTube-video
  91. // @description:vi Giảm tác động năng lượng của trình duyệt khi phát Video YouTube
  92. // @description:tr YouTube Videolarını Oynatırken Tarayıcının Enerji Etkisini Azaltın
  93. // @description:be Змяншыце энергетычны ўплыў браўзара на прайграванне YouTube-відэа
  94. // @description:bg Намалете енергийния влияние на браузъра при възпроизвеждане на видео в YouTube
  95. // @description:ky YouTube видеонун ойнотуусунан башкаруу үчүн браузердеги энергиялык турмуштарды көмүштөштүрүү
  96. // @description:kk YouTube-дың браузерде көрсету мүмкіндігін көмеге қысқартыңыз
  97. // @description:mk Намалете ја енергетската присутност на пребарувачот за репродукција на YouTube видео
  98. // @description:mn YouTube видеогийг тоглуулж буй хөтөчийн энерги хүчинг буурах
  99. // @description:uk Зменште енергетичний вплив браузера на відтворення відео на YouTube
  100. // @description:el Μειώστε την ενεργειακή επίδραση του προγράμματος περιήγησης για την αναπαραγωγή βίντεο στο YouTube
  101. // @description:hy Փոքրանալիքայինը դանդարեցրեք բրաուզերի էներգիայի ազդեցությունը YouTube վիդեոների ներածման դեպքում
  102. // @description:ur یوٹیوب ویڈیو کھیلنے کے لئے براؤزر کی توانائی پر اثر کم کریں
  103. // @description:ar تقليل تأثير استهلاك الطاقة لمتصفح تشغيل مقاطع فيديو يوتيوب
  104. // @description:fa کاهش تأثیر انرژی مرورگر برای پخش ویدئوی یوتیوب
  105. // @description:ne युट्युब भिडियो खेल्नका लागि ब्राउजरको ऊर्जा प्रभाव कम गर्नुहोस्
  106. // @description:mr YouTube व्हिडिओ चालवण्यासाठी ब्राउझरचे ऊर्जाचे प्रभाव कमी करा
  107. // @description:hi यूट्यूब वीडियो चलाने के लिए ब्राउज़र की ऊर्जा प्रभाव को कम करें
  108. // @description:as YouTube ভিডিঅ' প্ৰশ্ন কৰা ব্ৰাউজাৰৰ শক্তিৰ প্ৰভাৱ কমিয়া দিব
  109. // @description:bn YouTube ভিডিও চালাতে ব্রাউজারের শক্তি প্রভাব কমান
  110. // @description:pa YouTube ਵਿਡੀਓ ਚਲਾਉਣ ਲਈ ਬਰਾਉਜ਼ਰ ਦੀ ਊਰਜਾ ਪ੍ਰਭਾਵ ਘਟਾਓ
  111. // @description:gu YouTube વિડિઓ ચલાવવા માટે બ્રાઉઝરનું ઊર્જા પ્રભાવ ઘટાડો
  112. // @description:or YouTube ଭିଡିଓ ଚାଲାନ୍ତୁ ପାଇଁ ବ୍ରାଉଜରର ଶକ୍ତି ପ୍ରଭାବ କମାନ୍ତୁ
  113. // @description:ta யூடியூப் வீடியோவை இயக்குவதற்கான உலாவியின் மிக்க விளைவுகளை குறைக்கவும்
  114. // @description:te YouTube వీడియోను ప్రసారం చేయడానికి బ్రౌజర్ యొక్క శక్తి ప్రభావాన్ని తగ్గించుకోండి
  115. // @description:kn YouTube ವೀಡಿಯೊಗಳನ್ನು ಪ್ರದರ್ಶಿಸಲು ಬ್ರೌಸರ್ ಯನ್ನು ಉಪಯೋಗಿಸುವಾಗ ಶಕ್ತಿ ಪ್ರಭಾವವನ್ನು ಕಡಿಮೆಗೊಳಿಸಿ
  116. // @description:ml YouTube വീഡിയോ പ്രവർത്തിപ്പിക്കുവാൻ ബ്രൗസർയുടെ പ്രഭാവം കുറയ്ക്കുക
  117. // @description:si YouTube වීඩියෝ චාරිකා කිරීම සඳහා බ්‍රවුසරයේ ඊම්ජි බලන්න
  118. // @description:th ลดผลกระทบทางพลังงานของเบราว์เซอร์ในการเล่นวิดีโอ YouTube
  119. // @description:lo ບຣາຣິໂຄດລາວເອີ້ນໃນການເພີ່ມເວັບວຽກຂອງ YouTube ສຳ ລັບການຂະໜາດໃນການເພີ່ມເວັບວຽກ
  120. // @description:my YouTube ဗီဒီယိုများကို ဖွင့်ရန် Browser အတွက် Energy Impact ကိုအနိုင်ရန်
  121. // @description:ka YouTube ვიდეოების დაკვრებისას ბრაუზერის ენერგიის შეცვლა
  122. // @description:am YouTube ቪዲዮዎችን ለመቀነስ የባህሪውን አርእስት ግንኙነት ማድረግ
  123. // @description:km បង្កើតការធ្វើបរិមាណលំអិតរបស់ការកំណត់ការដាក់នៅលើសម្ពាធរបស់ប្រព័ន្ធបញ្ចូលបន្ទាត់ YouTube
  124. // ==/UserScript==
  125.  
  126. /* jshint esversion:8 */
  127.  
  128. /**
  129. *
  130. * This script does not support the following syntax intentionally.
  131. *
  132. * - string parameter as TimerHandler
  133. * e.g. setTimeout("console.log('300ms')", 300)
  134. * - no delay for `setInterval`
  135. * e.g. setInterval(f)
  136. *
  137. */
  138.  
  139. /**
  140. @typedef TimerObject
  141. @type {Object}
  142. @property {Function} handler
  143. @property {number?} timeout
  144. @property {number?} interval
  145. @property {number} nextAt
  146.  
  147. */
  148.  
  149. ((__CONTEXT__) => {
  150. 'use strict';
  151.  
  152. const UNDERCLOCK = +localStorage.cpuTamerUnderclock || 10; // default 10ms; increase to make the timer less responsive.
  153.  
  154. // "UNDERCLOCK" is set at 10ms by default. You can increase it to avoid unnecessary timer callbacks.
  155. // Suggested values: 10ms, 16ms, 24ms, 32ms, 48ms, 64ms.
  156. // Note: The script is not designed to operate with values higher 200ms. Please be careful of changing UNDERCLOCK value.
  157.  
  158. const win = this instanceof Window ? this : window;
  159.  
  160. // Create a unique key for the script and check if it is already running
  161. const hkey_script = 'nzsxclvflluv';
  162. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  163. win[hkey_script] = true;
  164.  
  165. /** @type {globalThis.PromiseConstructor} */
  166. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  167. const cleanContext = async (win) => {
  168. const waitFn = requestAnimationFrame; // shall have been binded to window
  169. try {
  170. let mx = 16; // MAX TRIAL
  171. const frameId = 'vanillajs-iframe-v1'
  172. let frame = document.getElementById(frameId);
  173. let removeIframeFn = null;
  174. if (!frame) {
  175. frame = document.createElement('iframe');
  176. frame.id = 'vanillajs-iframe-v1';
  177. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  178. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  179. n.appendChild(frame);
  180. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  181. const root = document.documentElement;
  182. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  183. removeIframeFn = (setTimeout) => {
  184. const removeIframeOnDocumentReady = (e) => {
  185. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  186. win = null;
  187. setTimeout(() => {
  188. n.remove();
  189. n = null;
  190. }, 200);
  191. }
  192. if (document.readyState !== 'loading') {
  193. removeIframeOnDocumentReady();
  194. } else {
  195. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  196. }
  197. }
  198. }
  199. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  200. const fc = frame.contentWindow;
  201. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  202. const { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout } = fc;
  203. const res = { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout };
  204. for (let k in res) res[k] = res[k].bind(win); // necessary
  205. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  206. return res;
  207. } catch (e) {
  208. console.warn(e);
  209. return null;
  210. }
  211. };
  212.  
  213. cleanContext(win).then(__CONTEXT__ => {
  214. if (!__CONTEXT__) return null;
  215.  
  216. // Create a symbol to represent the busy state of a handler function
  217. const $busy = Symbol('$busy');
  218.  
  219. // Define some constants for the initial value and the safe limits of the timer ID
  220. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  221. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  222. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  223. // Note: Number.MAX_SAFE_INTEGER = 9007199254740991
  224.  
  225. // Assign the Promise constructor to a local variable
  226. const { requestAnimationFrame, setTimeout, setInterval, clearTimeout, clearInterval } = __CONTEXT__;
  227.  
  228. const consoleError = e => console.error(e);
  229. const onPromiseErrorFn = (e) => { Promise.resolve(e).then(consoleError); }; // Promise will be resolved for Promise.all
  230.  
  231. // Define a flag to indicate whether the function handlers need to be reset
  232. let toResetFuncHandlers = false;
  233. let intervalTimerResolve = null;
  234.  
  235. const [sb, rm] = (() => {
  236.  
  237. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  238.  
  239. /** @type { Map<number, TimerObject> } */
  240. const sb = new Map(); // map of timer objects
  241.  
  242. /**
  243. * Define a helper function to create a timer object with a handler, a delay and a next execution time
  244. * @param {string} prop timeout / interval
  245. * @returns
  246. */
  247. const sFunc = (prop) => {
  248. /**
  249. * @param {Function} func TimerHandler
  250. * @param {number?} ms TimerHandler
  251. * @param {any[]} args
  252. */
  253. return (func, ms, ...args) => {
  254. mi++; // start at {INT_INITIAL_VALUE + 1}
  255. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  256. if (ms > SAFE_INT_LIMIT) return mi;
  257. if (typeof func === 'function') { // ignore all non-function parameter (e.g. string)
  258.  
  259. const hasArgs = args.length > 0;
  260.  
  261. let handler = hasArgs ? func.bind(null, ...args) : func; // original func if no extra argument
  262. handler[$busy] || (handler[$busy] = 0);
  263. sb.set(mi, {
  264. handler,
  265. [prop]: ms, // timeout / interval; value can be undefined
  266. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  267. });
  268. }
  269. return mi;
  270. };
  271. };
  272.  
  273. /**
  274. * Define a helper function to remove a timer object from the map or call the native method if not found
  275. * @param {number} jd timeoutID / intervalID
  276. * @returns
  277. */
  278. const rm = function (jd) {
  279. if (!jd) return; // native setInterval & setTimeout start from 1
  280. if (typeof jd === 'string') jd = +jd;
  281. const o = sb.get(jd);
  282. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  283. let action = jd <= INT_INITIAL_VALUE;
  284. if (action) {
  285. const nativeFn = this.nativeFn; // de::this
  286. nativeFn(jd); // only for clearTimeout & clearInterval
  287. }
  288. } else {
  289. for (const k in o) o[k] = null;
  290. sb.delete(jd);
  291. }
  292. };
  293.  
  294. // Override the window methods for setTimeout and setInterval with custom functions that use the helper function sFunc
  295. win.setTimeout = sFunc('timeout');
  296. win.setInterval = sFunc('interval');
  297.  
  298. // Override the window methods for clearTimeout and clearInterval with custom functions that use the helper function rm
  299. win.clearTimeout = rm.bind({
  300. nativeFn: clearTimeout
  301. });
  302. win.clearInterval = rm.bind({
  303. nativeFn: clearInterval
  304. });
  305.  
  306. // Try to override the toString methods of the window methods with the native ones
  307. try {
  308. win.setTimeout.toString = setTimeout.toString.bind(setTimeout)
  309. win.setInterval.toString = setInterval.toString.bind(setInterval)
  310. win.clearTimeout.toString = clearTimeout.toString.bind(clearTimeout)
  311. win.clearInterval.toString = clearInterval.toString.bind(clearInterval)
  312. } catch (e) { console.warn(e) }
  313.  
  314. return [sb, rm];
  315.  
  316. })();
  317.  
  318. /** @type {Function|null} */
  319. let nonResponsiveResolve = null;
  320. /** @type {(resolve: () => void)} */
  321. const delayNonResponsive = (resolve) => (nonResponsiveResolve = resolve);
  322.  
  323. /** @param {Function} handler */
  324. const pfMicroFn = (handler) => {
  325. // For function handler with high energy impact, discard 1st, 2nd, ... (n-1)th calling: (a,b,c,a,b,d,e,f) => (c,a,b,d,e,f)
  326. // For function handler with low energy impact, discard or not discard depends on system performance
  327. if (handler[$busy] === 1) handler();
  328. // error in handler would stop the following code execution and jump out to the Promise.all considered as "resolved" due to ignorePromiseErrorFn
  329. handler[$busy]--;
  330. };
  331.  
  332. /**
  333. *
  334. * @param {Function} handler
  335. */
  336. const pf = (
  337. handler => Promise.resolve(handler).then(pfMicroFn).catch(onPromiseErrorFn) // catch here to avoid no resolve to the race promise & avoid immediate end of the promise.all
  338. );
  339.  
  340. // Define a variable to store the next background execution time
  341. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  342.  
  343. // Define a variable to store the active page state
  344. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  345.  
  346. /** @type {Function|null} */
  347. let afInterupter = null;
  348.  
  349. function executeNow() {
  350. // in order to immediate fire setTimeout(..., 0) when livestream is paused (laggy)
  351.  
  352. if (nonResponsiveResolve !== null) {
  353. nonResponsiveResolve();
  354. }
  355.  
  356. if (intervalTimerResolve !== null) {
  357. intervalTimerResolve();
  358. intervalTimerResolve = null;
  359. }
  360.  
  361. const dInterupter = afInterupter;
  362. if (dInterupter !== null) {
  363. afInterupter = null;
  364. bgExecutionAt = Date.now() + 230;
  365. dInterupter();
  366. }
  367.  
  368. }
  369.  
  370. const getRAFHelper = () => {
  371. const asc = document.createElement('a-f');
  372. if (!('onanimationiteration' in asc)) {
  373. return (resolve) => requestAnimationFrame(afInterupter = resolve);
  374. }
  375. asc.id = 'a-f';
  376. let qr = null;
  377. asc.onanimationiteration = function () {
  378. if (qr !== null) {
  379. qr();
  380. qr = null;
  381. }
  382. }
  383. const style = document.createElement('style');
  384. style.textContent = `
  385. @keyFrames aF1 {
  386. 0% {
  387. order: 0;
  388. }
  389. 100% {
  390. order: 6;
  391. }
  392. }
  393. #a-f[id] {
  394. visibility: collaspe !important;
  395. position: fixed !important;
  396. top: -100px !important;
  397. left: -100px !important;
  398. margin:0 !important;
  399. padding:0 !important;
  400. outline:0 !important;
  401. border:0 !important;
  402. z-index:-1 !important;
  403. width: 0px !important;
  404. height: 0px !important;
  405. contain: strict !important;
  406. pointer-events: none !important;
  407. animation: 1ms steps(2) 0ms infinite alternate forwards running aF1 !important;
  408. }
  409. `;
  410. (document.head || document.documentElement).appendChild(style);
  411. document.documentElement.insertBefore(asc, document.documentElement.firstChild);
  412. return (resolve) => (qr = afInterupter = resolve);
  413. };
  414.  
  415.  
  416. /** @type {(resolve: () => void)} */
  417. const infiniteLooper = getRAFHelper(); // rAF will not execute if document is hidden
  418.  
  419. /** @type {(aHandlers: Function[])} */
  420. const microTaskExecutionActivePage = (aHandlers) => Promise.all(aHandlers.map(pf));
  421.  
  422. /** @type {(aHandlers: Function[])} */
  423. const microTaskExecutionBackgroundPage = (aHandlers) => {
  424. // error would not affect calling the next tick
  425. aHandlers.forEach(pf); // microTasks
  426. aHandlers.length = 0;
  427. };
  428.  
  429. const nextTickExecutionMT1 = async () => { // microTask #1
  430. const now = Date.now();
  431. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  432. /** @type {Function[]} */
  433. const sHandlers = []; // an array of handlers being executed in this tick
  434. const lsb = sb; // vairable scope < global to local > for better performance
  435. lsb.forEach((sV, sK) => {
  436. const {
  437. handler,
  438. // timeout,
  439. interval,
  440. nextAt
  441. } = sV;
  442. if (now < nextAt) return;
  443. handler[$busy]++;
  444. sHandlers.push(handler);
  445. if (interval > 0) { // prevent undefined, zero, negative values
  446. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  447. if (nextAt + _interval > now) sV.nextAt += _interval;
  448. else if (nextAt + 2 * _interval > now) sV.nextAt += 2 * _interval;
  449. else if (nextAt + 3 * _interval > now) sV.nextAt += 3 * _interval;
  450. else if (nextAt + 4 * _interval > now) sV.nextAt += 4 * _interval;
  451. else if (nextAt + 5 * _interval > now) sV.nextAt += 5 * _interval;
  452. else sV.nextAt = now + _interval;
  453. } else {
  454. // sK in sb must > INT_INITIAL_VALUE
  455. rm(sK); // remove timeout
  456. }
  457. });
  458. await Promise.resolve();
  459. return sHandlers;
  460. }
  461.  
  462. /**
  463. *
  464. * @param {Function[]} sHandlers
  465. */
  466. const nextTickExecutionMT2 = async (sHandlers) => { // microTask #2
  467. if (sHandlers.length === 0) { // no handler functions
  468. // requestAnimationFrame when the page is active
  469. // execution interval is no less than AnimationFrame
  470. } else if (dexActivePage) {
  471.  
  472. // retFP: looping for all functions. First error leads resolve non-reachable;
  473. // the particular [$busy] will not reset to 0 normally
  474. const retFP = Promise.resolve(sHandlers).then(microTaskExecutionActivePage);
  475. // inside Promise (async function), error would not affect calling the next tick
  476.  
  477. const retNR = new Promise(delayNonResponsive);
  478. // for every 125ms, retNR probably resolve eariler than retFP
  479. // however it still be controlled by rAF (or 250ms) in the next looping
  480.  
  481. await Promise.race([retFP, retNR]); // continue either 125ms time limit reached or all working functions have been done
  482. sHandlers.length = 0;
  483. nonResponsiveResolve = null;
  484. } else {
  485. Promise.resolve(sHandlers).then(microTaskExecutionBackgroundPage);
  486. }
  487. };
  488.  
  489. // Add an event listener for when YouTube finishes navigating to a new page and set the flag to reset the function handlers
  490. document.addEventListener("yt-navigate-finish", () => {
  491. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  492. Promise.resolve().then(executeNow);
  493. }, true); // capturing event - to let it runs before all everything else.
  494.  
  495. let clearResolveAt = 0;
  496. setInterval(() => {
  497. if (intervalTimerResolve !== null && Date.now() >= clearResolveAt) {
  498. intervalTimerResolve();
  499. intervalTimerResolve = null;
  500. }
  501. }, 10);
  502. const pTimerFn = resolve => { intervalTimerResolve = resolve };
  503.  
  504. (async () => {
  505. while (true) {
  506. const tickerNow = Date.now();
  507. clearResolveAt = tickerNow + UNDERCLOCK;
  508. const pTimer = new Promise(pTimerFn); // CPU; time throttled
  509. bgExecutionAt = tickerNow + 160;
  510. await new Promise(infiniteLooper); // resolve by rAF or timer@250ms
  511. await pTimer; // resolve by timer@10ms
  512. if (afInterupter === null) {
  513. // triggered by setInterval
  514. dexActivePage = false;
  515. } else {
  516. // triggered by rAF
  517. afInterupter = null;
  518. if (dexActivePage === false) toResetFuncHandlers = true;
  519. dexActivePage = true;
  520. }
  521. if (toResetFuncHandlers) {
  522. // true if page change from hidden to visible OR yt-finish
  523. toResetFuncHandlers = false;
  524. for (const eb of sb.values()) eb.handler[$busy] = 0; // including the functions with error
  525. }
  526. const sHandlers = await nextTickExecutionMT1();
  527. await nextTickExecutionMT2(sHandlers);
  528. }
  529. })();
  530.  
  531. setInterval(() => {
  532. if (nonResponsiveResolve !== null) {
  533. nonResponsiveResolve();
  534. return;
  535. }
  536. // no response of requestAnimationFrame; e.g. running in background
  537. const dInterupter = afInterupter;
  538. let now;
  539. if (dInterupter !== null && (now = Date.now()) > bgExecutionAt) {
  540. // interupter not triggered by rAF
  541. afInterupter = null;
  542. bgExecutionAt = now + 230;
  543. dInterupter();
  544. }
  545. }, 125);
  546. // --- 2022.12.14 ---
  547. // 125ms for race promise 'nonResponsiveResolve' only; interupter still works with interval set by bgExecutionAt
  548. // Timer Throttling might be more serious since 125ms is used instead of 250ms
  549. // ---------------------
  550. // 4 times per second for background execution - to keep YouTube application functional
  551. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  552.  
  553.  
  554. })
  555.  
  556.  
  557. })(null);