Skip to content

Instantly share code, notes, and snippets.

@hogart
Created December 16, 2014 10:50
Show Gist options
  • Save hogart/4673fa064d0cfe4c355e to your computer and use it in GitHub Desktop.
Save hogart/4673fa064d0cfe4c355e to your computer and use it in GitHub Desktop.
setInterval with random intervals (in given bounds)
/**
* @author Konstantin Kitmanov <doctor.hogart@gmail.com>
* @license MIT
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) { // AMD anonymous module
define([], factory);
} else if (typeof exports === 'object') { // NodeJS/CommonJS-like module
module.exports = factory();
} else { // Browser globals (root is window)
root.randomInterval = factory();
}
}(this, function () {
'use strict';
/**
* Return random float number between min and max
* @param {Number} min inclusive
* @param {Number} max exclusive
* @returns {Number} random float number
*/
function randomInRange (min, max) {
return Math.random() * (max - min) + min;
}
/**
* Calls `callback` after random timeout between `min` and `max`
* @param {Function} callback timeout callback
* @param {Number} min minimal timeout
* @param {Number} max maximal timeout
* @returns {Function} function that cancels timeout
*/
function setRandomTimeout (callback, min, max) {
var timeout = setTimeout(callback, Math.floor(randomInRange(min, max)));
return function () {
clearTimeout(timeout);
};
}
/**
* Calls `callback` in random intervals between `min` and `max`
* @param {Function} callback interval callback
* @param {Number} min minimal interval
* @param {Number} max maximal interval
* @returns {Function} function that cancels interval
*/
function setRandomInterval (callback, min, max) {
var currentTimeout;
function onTimeout () {
callback();
currentTimeout = setRandomTimeout(onTimeout, min, max);
}
currentTimeout = setRandomTimeout(onTimeout, min, max);
return function () {
currentTimeout();
};
}
setRandomInterval.setRandomTimeout = setRandomTimeout;
setRandomInterval.randomInRange = randomInRange;
return setRandomInterval;
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment