-
-
Save tomlobato/eb2fcb6dfd6b0fc90aeaa7ac4932dc62 to your computer and use it in GitHub Desktop.
throttle and debounce commands in bash
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
#!/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