Created
December 16, 2014 10:50
-
-
Save hogart/4673fa064d0cfe4c355e to your computer and use it in GitHub Desktop.
setInterval with random intervals (in given bounds)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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