如何检测对象是否是间隔/超时?

对于node.js

var timer = setInterval(function(){console.log('hi')},1000); var notATimer = {}; var number = 2; detectTimer(timer) //returns true detectTimer(notATimer) //returns false detectTimer(number) //returns false 

有什么办法可靠地确定一个对象是否是一个间隔? 此外,如果检测方法的奖励点也适用于setTimeout。

在nodejs中, setTimeoutsetInterval返回Timeout实例。 该构造函数不会被导出,但您仍然可以访问它并使用它来检测计时器对象:

 const Timeout = setTimeout(function(){}, 0).constructor; function isTimer(t) { return t instanceof Timeout; } 

如果你不想这样做,你也可以使用鸭子打字,通过testing对象有什么属性。

setTimeoutsetInterval返回一个id引用(在浏览器中)。

在节点中,它们返回对Timeout对象的引用。

所以不行 ,没有办法确定返回的值是来自计时器还是来自浏览器某处的variables。

节点上,你可以在技术上对返回值的构造函数做instanceof Timeout检查,但是我个人不喜欢这样做。


然而,你可以将你的定时器实现包装在一些包装对象调用者中,然后你可以检查哪一个可以在节点上和客户端上工作。

例如:

 class Timer { constructor(callback, time) { this.timeId = setTimeout(callback, time); } clear() { clearTimeout(this.timeId); } } const time = new Timer(() => console.log('hi'), 1000); console.log(time instanceof Timer); // true 

正如其他人已经提到的那样,我不认为这是可能的。 但是,您可以创build一个类似的包装

 // Timeout, Interval, whatever class Interval { constructor(...args) { this.interval = setInterval(...args); // again, whatever fits your needs return this; } /* ... */ } 

其中,应用,将是

 const timer = new Interval(() => console.log('I am an interval'), 1000); console.log(timer instanceof Interval) // => true (It's an interval) 

现在,这只是一个基本的例子,但我希望它给你正确的想法。

我build议更改setTimeout和setInterval函数的JavaScript,我意识到事实之后,你也标记了这个node.js,所以这里只是一个JavaScript的答案,因为其他答案处理node.js很好

 window.originalSetTimeout=window.setTimeout; window.originalClearTimeout=window.clearTimeout; window.originalSetInterval=window.setInterval; window.originalClearInterval=window.clearInterval; window.setTimeout=function(func,delay) { ret=window.originalSetTimeout(func,delay); ret +='-timeout'; return ret; }; window.setInterval=function(func,delay) { ret=window.originalSetInterval(func,delay); ret +='-interval'; return ret; }; window.clearTimeout=function(timerID) { tid=timerID.split('-')[0]; window.originalClearTimeout(tid); }; window.clearInterval=function(timerID) { tid=timerID.split('-')[0]; window.originalClearInterval(tid); }; isTimeout=function(timerID) { t=timerID.split('-')[1]; if(t == "timeout") return true; return false; } isInterval=function(timerID) { t=timerID.split('-')[1]; if(t == "interval") return true; return false; } t=setTimeout(function(){console.log('here');},5000); if(isTimeout(t)) document.getElementById('mess').innerHTML+='<BR>t is a Timeout'; if(isInterval(t)) document.getElementById('mess').innerHTML+='<BR>t is an Interval'; p=setInterval(function(){console.log('Interval here');},5000); if(isTimeout(p)) document.getElementById('mess').innerHTML+='<BR>p is a Timeout'; if(isInterval(p)) document.getElementById('mess').innerHTML+='<BR>p is an Interval'; 
 <div id="mess"></div>