Skip to content

Instantly share code, notes, and snippets.

@medihack
Created April 23, 2023 10:07
Show Gist options
  • Save medihack/7af1f98ea468aa7ad00102c7d84c65d8 to your computer and use it in GitHub Desktop.
Save medihack/7af1f98ea468aa7ad00102c7d84c65d8 to your computer and use it in GitHub Desktop.
A python decorator to debounce async functions
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
@kiroshin
Copy link

kiroshin commented Oct 4, 2024

def async_throttle(wait):
    def decorator(func):
        task: asyncio.Task | None = None
        @wraps(func)
        async def throttle(*args, **kwargs):
            nonlocal task
            if task and not task.done():
                return
            async def call_func():
                await func(*args, **kwargs)
                await asyncio.sleep(wait)
            task = asyncio.create_task(call_func())
            return task
        return throttle
    return decorator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment