Rynti

setAccurateInterval

Apr 6th, 2014
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Written by Robert 'rynti' Böhm, free to use by anyone
  2.  
  3. // Repeats a given function in a given interval.
  4. // The difference between setAccurateInterval and setInterval is that this version
  5. // preserves the original interval, as for example if your start a function on
  6. // millisecond 0 with an interval of 1000, it will always try to execute the function
  7. // on millisecond 1000, then 2000, then 3000, etc.
  8. // The standard setInterval function however will always execute the given function,
  9. // then wait 1000 milliseconds until it executes the function again. If the function
  10. // always takes 20 milliseconds to process for instance, it will execute the given
  11. // function on millisecond 1000, then 2020, then 3040, then 4060, etc.
  12.  
  13. // The parameter allowChoking can be used to avoid the (by default enabled) choke-
  14. // prevention. This means that for example if you use an interval of 1 second, and
  15. // the function takes 1.5 seconds to process, with choke prevention the interval
  16. // will try to preserve the original interval, only executing the function on
  17. // second 1, then second 3, then second 5, etc.
  18.  
  19. // If you don't want to use the default setTimeout function for waiting, you can pass
  20. // your custom setTimeout function as a fourth parameter. The function parameters
  21. // should match with the ones of the original setTimeout one.
  22. function setAccurateInterval(callback, interval, allowChoking, timeoutFunction) {
  23.   if (!timeoutFunction) timeoutFunction = setTimeout;
  24.   var start = Date.now();
  25.   var tick = function () {
  26.     callback();
  27.     start += interval;
  28.     var target = start + interval;
  29.     var diff = target - Date.now();
  30.     if (!allowChoking) {
  31.       while (diff < 0) {
  32.         diff += interval;
  33.         start += interval;
  34.       }
  35.     }
  36.     timeoutFunction(tick, diff);
  37.   };
  38.   timeoutFunction(tick, interval);
  39. }
  40.  
  41. // Example usage of setAccurateInterval
  42. setAccurateInterval(function () {
  43.   // Print the current timestamp:
  44.   var start = Date.now();
  45.   console.log('Processing started at ' + start);
  46.  
  47.   // Do something time-intensive:
  48.   var s = "";
  49.   for (var i = 0; i < 10000000; i++) { s += "a"; }
  50.  
  51.   // Print how long the function took to process:
  52.   var end = Date.now();
  53.   console.log('Processing took ' + (end - start) + 'ms');
  54. }, 1000);
Advertisement
Add Comment
Please, Sign In to add comment