Skip to content

Instantly share code, notes, and snippets.

@niieani
Last active December 11, 2023 15:39
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save niieani/29a054eb29d5306b32ecdfa4678cbb39 to your computer and use it in GitHub Desktop.
Save niieani/29a054eb29d5306b32ecdfa4678cbb39 to your computer and use it in GitHub Desktop.
throttle and debounce commands in bash
#!/usr/bin/env bash
declare -i last_called=0
declare -i throttle_by=2
@throttle() {
local -i now=$(date +%s)
if (($now - $last_called >= $throttle_by))
then
"$@"
fi
last_called=$(date +%s)
}
@debounce() {
if [[ ! -f ./executing ]]
then
touch ./executing
"$@"
retVal=$?
{
sleep $throttle_by
if [[ -f ./on-finish ]]
then
"$@"
rm -f ./on-finish
fi
rm -f ./executing
} &
return $retVal
elif [[ ! -f ./on-finish ]]
then
touch ./on-finish
fi
}
# will execute twice:
@throttle echo test
@throttle echo test
@throttle echo test
sleep 3
@throttle echo test
# will execute twice, not more than once per $throttle_by seconds
@debounce echo test
@debounce echo test
@debounce echo test
@debounce echo test
wait $(jobs -p) # need to wait for the bg jobs to complete
@insign
Copy link

insign commented Dec 14, 2021

Thank you.

@jayenashar
Copy link

jayenashar commented Oct 28, 2022

please make a version using $SECONDS instead of $(date)

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