mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 04:17:35 +00:00
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).
This commit is contained in:
parent
f96e8e97e6
commit
cdcdc095df
1 changed files with 29 additions and 0 deletions
29
Userland/Libraries/LibCore/Debounce.h
Normal file
29
Userland/Libraries/LibCore/Debounce.h
Normal file
|
@ -0,0 +1,29 @@
|
|||
/*
|
||||
* Copyright (c) 2022, MacDue <macdue@dueutil.tech>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <LibCore/Timer.h>
|
||||
|
||||
namespace Core {
|
||||
|
||||
template<typename TFunction>
|
||||
auto debounce(TFunction function, int timeout)
|
||||
{
|
||||
RefPtr<Core::Timer> timer;
|
||||
return [=]<typename... T>(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();
|
||||
};
|
||||
};
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue