简体   繁体   English

编写一个函数,检查一个时间间隔内另一个函数将被调用多少次

[英]Write a function that checks how many times another function will be called in a time interval

Say I have a function that logs "Hello" every 500 ms. 假设我有一个每500毫秒记录一次“ Hello”的函数。

var logHello = function() {
  setInterval(function(){ 
    console.log("Hello"); 
  }, 500);
};

Is there a way to write another function that will check if logHello gets called more than or equal to 1 time every second(without modifying the original logHello function). 有没有办法编写另一个函数来检查logHello是否每秒被调用大于或等于1次(无需修改原始logHello函数)。

In this case it will return true because Hello will get logged 2 times in 1 seconds. 在这种情况下,它将返回true,因为Hello将在1秒内被记录2次。

I am assuming you want to do this for debug reasons, so I must warn you not to include this code in any production application, as it's really just meant for debugging. 我假设您出于调试原因要执行此操作,因此我必须警告您不要将此代码包含在任何生产应用程序中,因为它实际上仅用于调试。 It's very cool that our solution works however it overwrites native javascript functionality which is typically frowned upon because it can cause code to behave differently than expected if you alter a native functions behaviour. 我们的解决方案可以正常工作很酷,但是它会覆盖通常不被接受的本地javascript功能,因为如果您更改本地功能的行为,它可能导致代码的行为与预期的不同。

If it's a condition that you are not allowed to modify your code, you can simply overwrite javascript's setInterval , and use it as a "hook" into your function. 如果不允许您修改代码,则可以简单地覆盖javascript的setInterval ,并将其用作函数的“钩子”。 We will modify setInterval to now track the time difference (seconds) inbetween calls to your method. 我们将修改setInterval以现在跟踪对您的方法的调用之间的时间差(秒)。 We will then invoke and return the original setInterval method so that your code still works exactly as expected: 然后,我们将调用并返回原始的setInterval方法,以便您的代码仍然可以按预期工作:

// keep a pointer to the original setInterval function
var oldSetInterval = window.setInterval;

// we will create our own setInterval function and put logging in it
window.setInterval = function(block, interval) {
  var lastRunAt;
  return oldSetInterval(function() {
    // here is where we print how long it's been since the method last ran
    if(lastRunAt) {
      console.log("the interval last ran " + (Date.now()-lastRunAt)/1000 + " seconds ago");
    }
    lastRunAt = Date.now();
    block();
  }, interval);
}

And now running logHello() yields: 现在运行logHello()产生:

Hello
the interval last ran 0.504 seconds ago
Hello
the interval last ran 0.504 seconds ago
Hello
the interval last ran 0.505 seconds ago

This assumes you're running on the web. 假设您正在网络上运行。 If you're in node, replace references to window with globals . 如果在节点中,请使用globals替换对window引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM