简体   繁体   中英

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.

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).

In this case it will return true because Hello will get logged 2 times in 1 seconds.

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.

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. We will modify setInterval to now track the time difference (seconds) inbetween calls to your method. We will then invoke and return the original setInterval method so that your code still works exactly as expected:

// 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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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