utils function

sleep, waitUntil, tryCatch...

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/536561/1592185/utils%20function.js

  1. // ==UserScript==
  2. // @name utils function
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.0.1
  5. // @description sleep, waitUntil, tryCatch...
  6. // @author zhowiny
  7. // @match *://*/*
  8. // @icon data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='1em' height='1em' viewBox='0 0 24 24'%3E%3C!-- Icon from Material Design Icons by Pictogrammers - https://github.com/Templarian/MaterialDesign/blob/master/LICENSE --%3E%3Cpath fill='currentColor' d='M12.42 5.29c-1.1-.1-2.07.71-2.17 1.82L10 10h2.82v2h-3l-.44 5.07A4.001 4.001 0 0 1 2 18.83l1.5-1.5c.33 1.05 1.46 1.64 2.5 1.3c.78-.24 1.33-.93 1.4-1.74L7.82 12h-3v-2H8l.27-3.07a4.01 4.01 0 0 1 4.33-3.65c1.26.11 2.4.81 3.06 1.89l-1.5 1.5c-.25-.77-.93-1.31-1.74-1.38M22 13.65l-1.41-1.41l-2.83 2.83l-2.83-2.83l-1.43 1.41l2.85 2.85l-2.85 2.81l1.43 1.41l2.83-2.83l2.83 2.83L22 19.31l-2.83-2.81z'/%3E%3C/svg%3E
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. async function sleep(time) {
  13. return new Promise(resolve => setTimeout(resolve, time));
  14. }
  15.  
  16. async function waitUntil(condition, timeout) {
  17. return new Promise((resolve, reject) => {
  18. const t = Date.now();
  19. const raf = async () => {
  20. if (await condition()) {
  21. resolve();
  22. } else if (timeout > 0 && Date.now() - t > timeout) {
  23. reject({message: `timeout(${timeout})`});
  24. } else {
  25. requestAnimationFrame(raf);
  26. }
  27. }
  28. requestAnimationFrame(raf);
  29. });
  30. }
  31.  
  32. async function tryCatch(promise) {
  33. try {
  34. const data = await promise;
  35. return { data, error: null };
  36. } catch (error) {
  37. return { data: null, error: error };
  38. }
  39. }
  40.  
  41. (function() {
  42. 'use strict';
  43. window.__utils__ = {
  44. sleep,
  45. waitUntil,
  46. tryCatch,
  47. }
  48. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址