Javascript运行时间函数观察者
问题描述:
我想知道如果和如何可以写一个function
观察其他功能。 更精确地,obsever
跟踪的所述observed
功能执行时间,并且如果后者超过给定的时间值时,observer
功能停止它。Javascript运行时间函数观察者
所以,简单地:
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 Workers。如果您使用Web Worker运行observed
,则主脚本可以在该worker上调用terminate()。
通常(至少在历史上)Javascript是single threaded,所以虽然observed
正在运行,但observer
无法阻止它。
我不认为有可能在外部停止函数的执行 - 您必须在您的observed()函数中建立超时。 –