Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Written by Robert 'rynti' Böhm, free to use by anyone
- // Repeats a given function in a given interval.
- // The difference between setAccurateInterval and setInterval is that this version
- // preserves the original interval, as for example if your start a function on
- // millisecond 0 with an interval of 1000, it will always try to execute the function
- // on millisecond 1000, then 2000, then 3000, etc.
- // The standard setInterval function however will always execute the given function,
- // then wait 1000 milliseconds until it executes the function again. If the function
- // always takes 20 milliseconds to process for instance, it will execute the given
- // function on millisecond 1000, then 2020, then 3040, then 4060, etc.
- // The parameter allowChoking can be used to avoid the (by default enabled) choke-
- // prevention. This means that for example if you use an interval of 1 second, and
- // the function takes 1.5 seconds to process, with choke prevention the interval
- // will try to preserve the original interval, only executing the function on
- // second 1, then second 3, then second 5, etc.
- // If you don't want to use the default setTimeout function for waiting, you can pass
- // your custom setTimeout function as a fourth parameter. The function parameters
- // should match with the ones of the original setTimeout one.
- function setAccurateInterval(callback, interval, allowChoking, timeoutFunction) {
- if (!timeoutFunction) timeoutFunction = setTimeout;
- var start = Date.now();
- var tick = function () {
- callback();
- start += interval;
- var target = start + interval;
- var diff = target - Date.now();
- if (!allowChoking) {
- while (diff < 0) {
- diff += interval;
- start += interval;
- }
- }
- timeoutFunction(tick, diff);
- };
- timeoutFunction(tick, interval);
- }
- // Example usage of setAccurateInterval
- setAccurateInterval(function () {
- // Print the current timestamp:
- var start = Date.now();
- console.log('Processing started at ' + start);
- // Do something time-intensive:
- var s = "";
- for (var i = 0; i < 10000000; i++) { s += "a"; }
- // Print how long the function took to process:
- var end = Date.now();
- console.log('Processing took ' + (end - start) + 'ms');
- }, 1000);
Advertisement
Add Comment
Please, Sign In to add comment