Created
April 23, 2023 10:07
-
-
Save medihack/7af1f98ea468aa7ad00102c7d84c65d8 to your computer and use it in GitHub Desktop.
A python decorator to debounce async functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from functools import wraps | |
def async_debounce(wait): | |
def decorator(func): | |
task = None | |
@wraps(func) | |
async def debounced(*args, **kwargs): | |
nonlocal task | |
async def call_func(): | |
await asyncio.sleep(wait) | |
await func(*args, **kwargs) | |
if task and not task.done(): | |
task.cancel() | |
task = asyncio.create_task(call_func()) | |
return task | |
return debounced | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment