Javascript运行时间函数观察者

Javascript elapsed time function observer

本文关键字:观察者 函数 运行时间 Javascript      更新时间:2023-09-26

我想知道如果如何可以编写一个观察其他函数的function。更准确地说,obsever跟踪observed函数的执行时间,当后者超过给定的时间值时,observer函数停止

所以,简要:

function observed() { // ... }
/**
 * Run a function and stop if this exceeds a given time.
 *
 * @param {Function} observedFunc The function to run and observe.
 * @param {Number} maxTime The maximum elapsed time allowed.
 */
function observer(observedFunc, maxTime) {
   /*
    * if (observedFunc exceed the time) 
    *     stop observedFunc;
    *     return;
    * else
    *     return; (when the observed function return)
    */
}

是否有可能在不改变observed功能的情况下负担得起?

只能在支持它的浏览器中使用Web worker。如果你在一个Web Worker中运行observed,那么主脚本可以在Worker上调用terminate()。

通常(至少历史上)Javascript是单线程的,因此当observed运行时,observer无法停止它。