From cdcdc095df47c30d140d9d612390981d673141e9 Mon Sep 17 00:00:00 2001 From: MacDue Date: Mon, 18 Jul 2022 20:00:03 +0100 Subject: [PATCH] LibCore: Add Core::debounce(function, timeout) This is a simple helper to debounce a function call, such as an event handler. It avoids the function being called until the event as settled down (i.e. after the timeout). --- Userland/Libraries/LibCore/Debounce.h | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Userland/Libraries/LibCore/Debounce.h diff --git a/Userland/Libraries/LibCore/Debounce.h b/Userland/Libraries/LibCore/Debounce.h new file mode 100644 index 0000000000..ba40a145bf --- /dev/null +++ b/Userland/Libraries/LibCore/Debounce.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022, MacDue + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include + +namespace Core { + +template +auto debounce(TFunction function, int timeout) +{ + RefPtr timer; + return [=](T... args) mutable { + auto apply_function = [=] { function(args...); }; + if (timer) { + timer->stop(); + timer->on_timeout = move(apply_function); + } else { + timer = Core::Timer::create_single_shot(timeout, move(apply_function)); + } + timer->start(); + }; +}; + +}