如何从外部覆盖 setTimeout

How to override setTimeout from outside

我们在项目中使用 require.js,我们需要重写 setTimeout 在第 1802 行,这是我们需要设置为 0 以某种方式完全忽略此 setTimeout(我的意思是它)的代码,问题是如果我在更改版本时在开源代码中显式更改它,代码将丢失,我应该如何从 outside 覆盖此 setTimout 仅用于 require.js 文件并在我使用这个库时保留它,是否可以在 JS 中以优雅的方式完成它?

/**
 * Execute something after the current tick
 * of the event loop. Override for other envs
 * that have a better solution than setTimeout.
 * @param  {Function} fn function to execute later.
 */
req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
    setTimeout(fn, 4);
} : function (fn) { fn(); };

这是 Git 中 require.js 开源的 link https://github.com/jrburke/requirejs/blob/master/require.js 第 1802 行

require 对象公开为全局变量,因此您可以像这样重写它的方法:

window.require.nextTick = function(fn) {
  setTimeout(fn, 0);
}

但我想不出这样做有什么好的理由。


但是,这不会解决您的问题,因为 setTimeout 调用无论如何都会受到浏览器的限制。更好的选择是简单地调用函数:

window.require.nextTick = function(fn) { fn(); };

您可以在 require 的源代码中看到,原始 nextTick 函数可以有两种实现,具体取决于 setTimeout 可用性 - 一种使用 setTimeout ,另一种仅在 setTimeout 未定义时使用函数调用(您粘贴的代码段的最后一行)。这就是为什么我认为像上面那样重写这个函数不会造成任何问题。