joh/when-changed

Add minimum delay option for accepting new events

Closed this issue · 3 comments

Using vim as text editor makes saving (:w) text files trigger two events in a row (almost simultaneously), causing the command to be executed twice. It might be complicated to avoid this, and the file might be actually being written twice, so a suggestion would be to have an option to set a minimum delay to accept a new event after just triggering one.
One example of this is watching .css and .js files then running gulp when one of the files change, but gulp gets executed twice in a row after a single change in one of the files. I tested this in a single text file and it has the same behaviour, two events fired in a row. This happens when using vim, doesn't happen with Sublime Text or nano.

To test this:

touch myfile
# this prints the current system time in milliseconds when myfile is changed
when-changed myfile "echo $(($(date +%s%N)/1000000))"

# in another terminal
vim myfile
[do some change and save it by using :w]
[check the events, you'll see two events triggered in the same millisecond]

An idea is to have a flag to set a minimal delay for accepting a new event. So for example, if the delay is set to 1ms and the above case happens, we got two events being triggered but the second one is ignored because it triggered too fast (before first event + delay).

Again, this happens when saving a file in vim. Doesn't happen in Sublime Text and nano. Other editors have to be tested.

This delay could also useful in many other scenarios, in which you don't want to run the command two times in a row just because the file changed too fast.
Or maybe have support for something like an event queue (and avoid ignoring events triggered) with a minimal delay between each trigger.

joh commented

Hmm, did you try the -1 option?

Hmm, did you try the -1 option?

Oh! Life saving advice lol
That was so simple, thank you so much.
Please ignore my suggestion then :)

Hmm, did you try the -1 option?

Hi! I use -1 but there is not useful. Saving file by :w will get two events. My cmd line is when-changed -v -r -1 . -c go run main.go and then OS is Centos 7.

What can I do for it? Thank you in advance!