YouTube CPU Tamer by AnimationFrame

減少YouTube影片所致的能源消耗

目前為 2023-09-18 提交的版本,檢視 最新版本

  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.09.18.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 = frameId;
  177. const blobURL = typeof webkitCancelAnimationFrame === 'function' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  178. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  179. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  180. n.appendChild(frame);
  181. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  182. const root = document.documentElement;
  183. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  184. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  185.  
  186. removeIframeFn = (setTimeout) => {
  187. const removeIframeOnDocumentReady = (e) => {
  188. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  189. win = null;
  190. const m = n;
  191. n = null;
  192. setTimeout(() => m.remove(), 200);
  193. }
  194. if (document.readyState !== 'loading') {
  195. removeIframeOnDocumentReady();
  196. } else {
  197. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  198. }
  199. }
  200. }
  201. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  202. const fc = frame.contentWindow;
  203. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  204. const { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout } = fc;
  205. const res = { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout };
  206. for (let k in res) res[k] = res[k].bind(win); // necessary
  207. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  208. return res;
  209. } catch (e) {
  210. console.warn(e);
  211. return null;
  212. }
  213. };
  214.  
  215. cleanContext(win).then(__CONTEXT__ => {
  216. if (!__CONTEXT__) return null;
  217.  
  218. // Create a symbol to represent the busy state of a handler function
  219. const $busy = Symbol('$busy');
  220.  
  221. // Define some constants for the initial value and the safe limits of the timer ID
  222. const INT_INITIAL_VALUE = 8192; // 1 ~ {INT_INITIAL_VALUE} are reserved for native setTimeout/setInterval
  223. const SAFE_INT_LIMIT = 2251799813685248; // in case cid would be used for multiplying
  224. const SAFE_INT_REDUCED = 67108864; // avoid persistent interval handlers with cids between {INT_INITIAL_VALUE + 1} and {SAFE_INT_REDUCED - 1}
  225. // Note: Number.MAX_SAFE_INTEGER = 9007199254740991
  226.  
  227. // Assign the Promise constructor to a local variable
  228. const { requestAnimationFrame, setTimeout, setInterval, clearTimeout, clearInterval } = __CONTEXT__;
  229.  
  230. const consoleError = e => console.error(e);
  231. const onPromiseErrorFn = (e) => { Promise.resolve(e).then(consoleError); }; // Promise will be resolved for Promise.all
  232.  
  233. // Define a flag to indicate whether the function handlers need to be reset
  234. let toResetFuncHandlers = false;
  235. let intervalTimerResolve = null;
  236.  
  237. const [sb, rm] = (() => {
  238.  
  239. let mi = INT_INITIAL_VALUE; // skip first {INT_INITIAL_VALUE} cids to avoid browser not yet initialized
  240.  
  241. /** @type { Map<number, TimerObject> } */
  242. const sb = new Map(); // map of timer objects
  243.  
  244. /**
  245. * Define a helper function to create a timer object with a handler, a delay and a next execution time
  246. * @param {string} prop timeout / interval
  247. * @returns
  248. */
  249. const sFunc = (prop) => {
  250. /**
  251. * @param {Function} func TimerHandler
  252. * @param {number?} ms TimerHandler
  253. * @param {any[]} args
  254. */
  255. return (func, ms, ...args) => {
  256. mi++; // start at {INT_INITIAL_VALUE + 1}
  257. if (mi > SAFE_INT_LIMIT) mi = SAFE_INT_REDUCED; // just in case
  258. if (ms > SAFE_INT_LIMIT) return mi;
  259. if (typeof func === 'function') { // ignore all non-function parameter (e.g. string)
  260.  
  261. const hasArgs = args.length > 0;
  262.  
  263. let handler = hasArgs ? func.bind(null, ...args) : func; // original func if no extra argument
  264. handler[$busy] || (handler[$busy] = 0);
  265. sb.set(mi, {
  266. handler,
  267. [prop]: ms, // timeout / interval; value can be undefined
  268. nextAt: Date.now() + (ms > 0 ? ms : 0) // overload for setTimeout(func);
  269. });
  270. }
  271. return mi;
  272. };
  273. };
  274.  
  275. /**
  276. * Define a helper function to remove a timer object from the map or call the native method if not found
  277. * @param {number} jd timeoutID / intervalID
  278. * @returns
  279. */
  280. const rm = function (jd) {
  281. if (!jd) return; // native setInterval & setTimeout start from 1
  282. if (typeof jd === 'string') jd = +jd;
  283. const o = sb.get(jd);
  284. if (typeof o !== 'object') { // to clear the same cid is unlikely to happen || requiring nativeFn is unlikely to happen
  285. let action = jd <= INT_INITIAL_VALUE;
  286. if (action) {
  287. const nativeFn = this.nativeFn; // de::this
  288. nativeFn(jd); // only for clearTimeout & clearInterval
  289. }
  290. } else {
  291. for (const k in o) o[k] = null;
  292. sb.delete(jd);
  293. }
  294. };
  295.  
  296. // Override the window methods for setTimeout and setInterval with custom functions that use the helper function sFunc
  297. win.setTimeout = sFunc('timeout');
  298. win.setInterval = sFunc('interval');
  299.  
  300. // Override the window methods for clearTimeout and clearInterval with custom functions that use the helper function rm
  301. win.clearTimeout = rm.bind({
  302. nativeFn: clearTimeout
  303. });
  304. win.clearInterval = rm.bind({
  305. nativeFn: clearInterval
  306. });
  307.  
  308. // Try to override the toString methods of the window methods with the native ones
  309. try {
  310. win.setTimeout.toString = setTimeout.toString.bind(setTimeout)
  311. win.setInterval.toString = setInterval.toString.bind(setInterval)
  312. win.clearTimeout.toString = clearTimeout.toString.bind(clearTimeout)
  313. win.clearInterval.toString = clearInterval.toString.bind(clearInterval)
  314. } catch (e) { console.warn(e) }
  315.  
  316. return [sb, rm];
  317.  
  318. })();
  319.  
  320. /** @type {Function|null} */
  321. let nonResponsiveResolve = null;
  322. /** @type {(resolve: () => void)} */
  323. const delayNonResponsive = (resolve) => (nonResponsiveResolve = resolve);
  324.  
  325. /** @param {Function} handler */
  326. const pfMicroFn = (handler) => {
  327. // 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)
  328. // For function handler with low energy impact, discard or not discard depends on system performance
  329. if (handler[$busy] === 1) handler();
  330. // error in handler would stop the following code execution and jump out to the Promise.all considered as "resolved" due to ignorePromiseErrorFn
  331. handler[$busy]--;
  332. };
  333.  
  334. /**
  335. *
  336. * @param {Function} handler
  337. */
  338. const pf = (
  339. 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
  340. );
  341.  
  342. // Define a variable to store the next background execution time
  343. let bgExecutionAt = 0; // set at 0 to trigger tf in background startup when requestAnimationFrame is not responsive
  344.  
  345. // Define a variable to store the active page state
  346. let dexActivePage = true; // true for default; false when checking triggered by setInterval
  347.  
  348. /** @type {Function|null} */
  349. let afInterupter = null;
  350.  
  351. function executeNow() {
  352. // in order to immediate fire setTimeout(..., 0) when livestream is paused (laggy)
  353.  
  354. if (nonResponsiveResolve !== null) {
  355. nonResponsiveResolve();
  356. }
  357.  
  358. if (intervalTimerResolve !== null) {
  359. intervalTimerResolve();
  360. intervalTimerResolve = null;
  361. }
  362.  
  363. const dInterupter = afInterupter;
  364. if (dInterupter !== null) {
  365. afInterupter = null;
  366. bgExecutionAt = Date.now() + 230;
  367. dInterupter();
  368. }
  369.  
  370. }
  371.  
  372. const getRAFHelper = () => {
  373. const asc = document.createElement('a-f');
  374. if (!('onanimationiteration' in asc)) {
  375. return (resolve) => requestAnimationFrame(afInterupter = resolve);
  376. }
  377. asc.id = 'a-f';
  378. let qr = null;
  379. asc.onanimationiteration = function () {
  380. if (qr !== null) {
  381. qr();
  382. qr = null;
  383. }
  384. }
  385. const style = document.createElement('style');
  386. style.textContent = `
  387. @keyFrames aF1 {
  388. 0% {
  389. order: 0;
  390. }
  391. 100% {
  392. order: 6;
  393. }
  394. }
  395. #a-f[id] {
  396. visibility: collapse !important;
  397. position: fixed !important;
  398. top: -100px !important;
  399. left: -100px !important;
  400. margin:0 !important;
  401. padding:0 !important;
  402. outline:0 !important;
  403. border:0 !important;
  404. z-index:-1 !important;
  405. width: 0px !important;
  406. height: 0px !important;
  407. contain: strict !important;
  408. pointer-events: none !important;
  409. animation: 1ms steps(2) 0ms infinite alternate forwards running aF1 !important;
  410. }
  411. `;
  412. (document.head || document.documentElement).appendChild(style);
  413. document.documentElement.insertBefore(asc, document.documentElement.firstChild);
  414. return (resolve) => (qr = afInterupter = resolve);
  415. };
  416.  
  417.  
  418. /** @type {(resolve: () => void)} */
  419. const infiniteLooper = getRAFHelper(); // rAF will not execute if document is hidden
  420.  
  421. /** @type {(aHandlers: Function[])} */
  422. const microTaskExecutionActivePage = (aHandlers) => Promise.all(aHandlers.map(pf));
  423.  
  424. /** @type {(aHandlers: Function[])} */
  425. const microTaskExecutionBackgroundPage = (aHandlers) => {
  426. // error would not affect calling the next tick
  427. aHandlers.forEach(pf); // microTasks
  428. aHandlers.length = 0;
  429. };
  430.  
  431. const nextTickExecutionMT1 = async () => { // microTask #1
  432. const now = Date.now();
  433. // bgExecutionAt = now + 160; // if requestAnimationFrame is not responsive (e.g. background running)
  434. /** @type {Function[]} */
  435. const sHandlers = []; // an array of handlers being executed in this tick
  436. const lsb = sb; // vairable scope < global to local > for better performance
  437. lsb.forEach((sV, sK) => {
  438. const {
  439. handler,
  440. // timeout,
  441. interval,
  442. nextAt
  443. } = sV;
  444. if (now < nextAt) return;
  445. handler[$busy]++;
  446. sHandlers.push(handler);
  447. if (interval > 0) { // prevent undefined, zero, negative values
  448. const _interval = +interval; // convertion from string to number if necessary; decimal is acceptable
  449. if (nextAt + _interval > now) sV.nextAt += _interval;
  450. else if (nextAt + 2 * _interval > now) sV.nextAt += 2 * _interval;
  451. else if (nextAt + 3 * _interval > now) sV.nextAt += 3 * _interval;
  452. else if (nextAt + 4 * _interval > now) sV.nextAt += 4 * _interval;
  453. else if (nextAt + 5 * _interval > now) sV.nextAt += 5 * _interval;
  454. else sV.nextAt = now + _interval;
  455. } else {
  456. // sK in sb must > INT_INITIAL_VALUE
  457. rm(sK); // remove timeout
  458. }
  459. });
  460. await Promise.resolve();
  461. return sHandlers;
  462. }
  463.  
  464. /**
  465. *
  466. * @param {Function[]} sHandlers
  467. */
  468. const nextTickExecutionMT2 = async (sHandlers) => { // microTask #2
  469. if (sHandlers.length === 0) { // no handler functions
  470. // requestAnimationFrame when the page is active
  471. // execution interval is no less than AnimationFrame
  472. } else if (dexActivePage) {
  473.  
  474. // retFP: looping for all functions. First error leads resolve non-reachable;
  475. // the particular [$busy] will not reset to 0 normally
  476. const retFP = Promise.resolve(sHandlers).then(microTaskExecutionActivePage);
  477. // inside Promise (async function), error would not affect calling the next tick
  478.  
  479. const retNR = new Promise(delayNonResponsive);
  480. // for every 125ms, retNR probably resolve eariler than retFP
  481. // however it still be controlled by rAF (or 250ms) in the next looping
  482.  
  483. await Promise.race([retFP, retNR]); // continue either 125ms time limit reached or all working functions have been done
  484. sHandlers.length = 0;
  485. nonResponsiveResolve = null;
  486. } else {
  487. Promise.resolve(sHandlers).then(microTaskExecutionBackgroundPage);
  488. }
  489. };
  490.  
  491. // Add an event listener for when YouTube finishes navigating to a new page and set the flag to reset the function handlers
  492. document.addEventListener("yt-navigate-finish", () => {
  493. toResetFuncHandlers = true; // ensure all function handlers can be executed after YouTube navigation.
  494. Promise.resolve().then(executeNow);
  495. }, true); // capturing event - to let it runs before all everything else.
  496.  
  497. let clearResolveAt = 0;
  498. setInterval(() => {
  499. if (intervalTimerResolve !== null && Date.now() >= clearResolveAt) {
  500. intervalTimerResolve();
  501. intervalTimerResolve = null;
  502. }
  503. }, 10);
  504. const pTimerFn = resolve => { intervalTimerResolve = resolve };
  505.  
  506. (async () => {
  507. while (true) {
  508. const tickerNow = Date.now();
  509. clearResolveAt = tickerNow + UNDERCLOCK;
  510. const pTimer = new Promise(pTimerFn); // CPU; time throttled
  511. bgExecutionAt = tickerNow + 160;
  512. await new Promise(infiniteLooper); // resolve by rAF or timer@250ms
  513. await pTimer; // resolve by timer@10ms
  514. if (afInterupter === null) {
  515. // triggered by setInterval
  516. dexActivePage = false;
  517. } else {
  518. // triggered by rAF
  519. afInterupter = null;
  520. if (dexActivePage === false) toResetFuncHandlers = true;
  521. dexActivePage = true;
  522. }
  523. if (toResetFuncHandlers) {
  524. // true if page change from hidden to visible OR yt-finish
  525. toResetFuncHandlers = false;
  526. for (const eb of sb.values()) eb.handler[$busy] = 0; // including the functions with error
  527. }
  528. const sHandlers = await nextTickExecutionMT1();
  529. await nextTickExecutionMT2(sHandlers);
  530. }
  531. })();
  532.  
  533. setInterval(() => {
  534. if (nonResponsiveResolve !== null) {
  535. nonResponsiveResolve();
  536. return;
  537. }
  538. // no response of requestAnimationFrame; e.g. running in background
  539. const dInterupter = afInterupter;
  540. let now;
  541. if (dInterupter !== null && (now = Date.now()) > bgExecutionAt) {
  542. // interupter not triggered by rAF
  543. afInterupter = null;
  544. bgExecutionAt = now + 230;
  545. dInterupter();
  546. }
  547. }, 125);
  548. // --- 2022.12.14 ---
  549. // 125ms for race promise 'nonResponsiveResolve' only; interupter still works with interval set by bgExecutionAt
  550. // Timer Throttling might be more serious since 125ms is used instead of 250ms
  551. // ---------------------
  552. // 4 times per second for background execution - to keep YouTube application functional
  553. // if there is Timer Throttling for background running, the execution become the same as native setTimeout & setInterval.
  554.  
  555.  
  556. })
  557.  
  558.  
  559. })(null);