2

I'm very confused at the moment.

What I want to do is create a listener function, that wait for two commands - and the thing is it should only listen every two hundred milliseconds and ignore the other input from the user.

function foo() {

    read -sN1 _input

    case "${_input}" in

        A) echo 'Option A';;
        B) echo 'Option B';;
    esac
}

while true; do
    sleep 0.2
    foo
done

If I "hammer" the A-key (or UP-key) ten times, it writes "Option A" ten times (although, slowly) - when it should only had time to write it at most three times. Why is that - and how do I fix it?

1
  • 1
    You'll need a timeout on your read as well, or your program will wait indefinitely for input after the initial 200-ms sleep. Commented Aug 17, 2012 at 13:26

3 Answers 3

3

Your terminal buffers the input to your program. In order to make your program ignore the input it received while it sleeps, you should clear the input buffer before calling read. To my knowledge there is not way to do this in bash.

Sign up to request clarification or add additional context in comments.

Comments

0

You can put your sleep function within a block where stdin is closed:

  {
    sleep 0.2
  } <&- 

Alternatively, you can clear (read and discard) the stdin buffer right after the sleep:

sleep 0.2
read -t 1 -n 10000 discard

1 Comment

this sounds like a good idea, never got it to work though. It somehow messes with the second read command and nothing gets read. However, I came up with a different solution - see below.
0

This is what I came up with that worked. It isn't very nice, but it works.

function inputCommand() {

    _now=`date +%s%N | cut -b1-13`
    _time=$(($_now-$_timeout))

    if [ $_time -gt 500 ]; then
            $1
            _timeout=`date +%s%N | cut -b1-13`
    fi
}

function keyPressUp() {

    echo "Key Press Up"
}

function waitForInput() {

    unset _input
    read -sN1 _input

    case "${_input}" in

            A) inputCommand "keyPressUp";;
    esac
}

while true; do

        waitForInput
done

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.