Is it possible to wait to run a midi trigger until the value has stopped changing?

Hello folks!

I'm using a simple 4 knob midi device to trigger a Shortcut (the capital S macOS built-in Shortcuts app kind) with the intention of adjusting volumes in Rogue Amoeba's SoundSource app, which has Shortcuts support. Basically I use a midi trigger in BTT which calls some applescript I wrote, which itself calls the Shortcut.

Here's the trigger:

Here's the applescript:

on bttMIDIValuechanged(midiValue)
	set shortcutName to "Firefox Volume"
	if (midiValue < 15) then
		set volumeLevel to 0
	else if (midiValue > 112) then
		set volumeLevel to 100
		set volumeLevel to (midiValue / 127) * 100
	end if
	tell application "Shortcuts Events"
		run the shortcut shortcutName with input volumeLevel
	end tell
end bttMIDIValuechanged

The problem I'm running into is that Shortcuts is kind of slow, so basically it will sometimes adjust the volume out of order. I've mitigated this slightly by setting the trigger to only run when the value is changed by 15 or more, but this is often still too fast for Shortcuts to keep up, and will result in my volume jumping around wildly. Here's a gif of what it looks like when I turn the knob from 0 to 100 to see what I'm talking about:

Capture 2022-06-07T124905

You can see in this particular example that it looks like Shortcuts processed the set volume to 27% command last, so while I tried to adjust the volume to 100%, that didn't work out. I think this is what programmers who actually know what they are doing may call a race condition :slight_smile:

Can anyone think of a better way for me to set this up to? It would be nice if BTT had an option to sort of wait for the midi value to stay constant for a second, but maybe there is something I could do in my applescript to improve this.