YouTube CPU Tamer by AnimationFrame

Reduce Browser's Energy Impact for playing YouTube Video

As of 2023-07-19. See the latest version.

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