|
| 1 | +/** |
| 2 | +* Copyright 2012-2017, Plotly, Inc. |
| 3 | +* All rights reserved. |
| 4 | +* |
| 5 | +* This source code is licensed under the MIT license found in the |
| 6 | +* LICENSE file in the root directory of this source tree. |
| 7 | +*/ |
| 8 | + |
| 9 | +'use strict'; |
| 10 | + |
| 11 | +var timerCache = {}; |
| 12 | + |
| 13 | +/** |
| 14 | + * Throttle a callback. `callback` executes synchronously only if |
| 15 | + * more than `minInterval` milliseconds have already elapsed since the latest |
| 16 | + * call (if any). Otherwise we wait until `minInterval` is over and execute the |
| 17 | + * last callback received while waiting. |
| 18 | + * So the first and last events in a train are always executed (eventually) |
| 19 | + * but some of the events in the middle can be dropped. |
| 20 | + * |
| 21 | + * @param {function} callback: the function to throttle |
| 22 | + * @param {string} id: an identifier to mark events to throttle together |
| 23 | + * @param {number} minInterval: minimum time, in milliseconds, between |
| 24 | + * invocations of `callback` |
| 25 | + */ |
| 26 | +exports.throttle = function throttle(callback, minInterval, id) { |
| 27 | + var cache = timerCache[id]; |
| 28 | + var now = Date.now(); |
| 29 | + |
| 30 | + if(!cache) { |
| 31 | + /* |
| 32 | + * Throw out old items before making a new one, to prevent the cache |
| 33 | + * getting overgrown, for example from old plots that have been replaced. |
| 34 | + * 1 minute age is arbitrary. |
| 35 | + */ |
| 36 | + for(var idi in timerCache) { |
| 37 | + if(timerCache[idi].ts < now - 60000) { |
| 38 | + delete timerCache[idi]; |
| 39 | + } |
| 40 | + } |
| 41 | + cache = timerCache[id] = {ts: 0, timer: null}; |
| 42 | + } |
| 43 | + |
| 44 | + _clearTimeout(cache); |
| 45 | + |
| 46 | + if(now > cache.ts + minInterval) { |
| 47 | + callback(); |
| 48 | + cache.ts = now; |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + cache.timer = setTimeout(function() { |
| 53 | + callback(); |
| 54 | + cache.ts = Date.now(); |
| 55 | + cache.timer = null; |
| 56 | + }, minInterval); |
| 57 | +}; |
| 58 | + |
| 59 | +/** |
| 60 | + * Clear the throttle cache for one or all timers |
| 61 | + * @param {optional string} id: |
| 62 | + * if provided, clear just this timer |
| 63 | + * if omitted, clear all timers (mainly useful for testing) |
| 64 | + */ |
| 65 | +exports.clear = function(id) { |
| 66 | + if(id) { |
| 67 | + _clearTimeout(timerCache[id]); |
| 68 | + delete timerCache[id]; |
| 69 | + } |
| 70 | + else { |
| 71 | + for(var idi in timerCache) exports.clear(idi); |
| 72 | + } |
| 73 | +}; |
| 74 | + |
| 75 | +function _clearTimeout(cache) { |
| 76 | + if(cache && cache.timer !== null) { |
| 77 | + clearTimeout(cache.timer); |
| 78 | + cache.timer = null; |
| 79 | + } |
| 80 | +} |
0 commit comments