Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.