From d1340f1b85b63ae4866cfd2939e3162149594a72 Mon Sep 17 00:00:00 2001 From: nobuti Date: Thu, 12 Jan 2017 09:46:53 +0100 Subject: [PATCH] Debounce FTW. --- src/js/lib/helper.js | 20 ++++++++++++++++++++ src/js/plugin/resizer.js | 5 +++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/js/lib/helper.js b/src/js/lib/helper.js index a9f0163..609b345 100644 --- a/src/js/lib/helper.js +++ b/src/js/lib/helper.js @@ -23,6 +23,26 @@ var clone = exports.clone = function (obj) { } }; +exports.debounce = function (func, wait, immediate) { + var timeout; + return function () { + var context = this; + var args = arguments; + var later = function () { + timeout = null; + if (!immediate) { + func.apply(context, args); + } + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) { + func.apply(context, args); + } + }; +}; + exports.extend = function (original, source) { var result = clone(original); for (var key in source) { diff --git a/src/js/plugin/resizer.js b/src/js/plugin/resizer.js index 84b4497..74074ea 100644 --- a/src/js/plugin/resizer.js +++ b/src/js/plugin/resizer.js @@ -2,13 +2,14 @@ var update = require('./update'); var instances = require('./instances'); +var _ = require('../lib/helper'); module.exports = function (element) { var i = instances.get(element); - var onMutationObserver = function () { + var onResize = function () { update(element); }; - i.event.bind(window, 'resize', onMutationObserver); + i.event.bind(window, 'resize', _.debounce(onResize, 60)); };