From 1de4944d46010e714e51d60d469ca66fef2e9233 Mon Sep 17 00:00:00 2001 From: nolialsea Date: Fri, 25 Mar 2022 20:08:56 +0100 Subject: [PATCH] Add throttle closure for settings sliders Adds a throttling closure to add a waiting time before calling a callback, Uses this closure to throttle the event fired by socketio on slider value change --- static/application.js | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/static/application.js b/static/application.js index 88637075..b5d6ba36 100644 --- a/static/application.js +++ b/static/application.js @@ -118,10 +118,32 @@ var adventure = false; // Chatmode var chatmode = false; +var sliders_throttle = getThrottle(250); + //=================================================================// // METHODS //=================================================================// +/** + * Returns a function that will automatically wait for X ms before executing the callback + * The timer is reset each time the returned function is called + * Useful for methods where something is overridden too fast + * @param ms milliseconds to wait before executing the callback + * @return {(function(*): void)|*} function that takes the ms to wait and a callback to execute after the timer + */ +function getThrottle(ms) { + var timer; + + return function (callback) { + if (timer) { + clearTimeout(timer); + } + timer = setTimeout(function () { + callback(); + }, ms); + } +} + function addSetting(ob) { // Add setting block to Settings Menu if(ob.uitype == "slider"){ @@ -153,8 +175,11 @@ function addSetting(ob) { window["label_"+ob.id] = reflb; // Is this still needed? // Add event function to input refin.on("input", function () { - socket.send({'cmd': $(this).attr('id'), 'data': $(this).val()}); - }); + sliders_throttle(function () { + socket.send({'cmd': $(this).attr('id'), 'data': $(this).val()}); + }); + } + ); } else if(ob.uitype == "toggle"){ settings_menu.append("
\ \