Last active
September 21, 2024 21:50
-
-
Save niieani/29a054eb29d5306b32ecdfa4678cbb39 to your computer and use it in GitHub Desktop.
throttle and debounce commands in bash
This file contains hidden or 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 |
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
Thank you.