Skip to content

Instantly share code, notes, and snippets.

@tomlobato
Forked from niieani/throttle-and-debounce.sh
Created February 2, 2018 17:38
Show Gist options
  • Save tomlobato/eb2fcb6dfd6b0fc90aeaa7ac4932dc62 to your computer and use it in GitHub Desktop.
Save tomlobato/eb2fcb6dfd6b0fc90aeaa7ac4932dc62 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment