Read numbers and characters from the keyboard

I’d welcome some pointers to relevant examples to create a simple egg timer that parses input from the keyboard as follows:

  • ‘s’ sets the unit to seconds (default);
  • ‘m’ sets the unit to minutes (effectively multiplying the delay by 60);
  • space’ toggles the timer’s pause;
  • a string of digits typed in quick succession (within half a second) results in a number.

To capture a string of digits as a number, my current thoughts are in the direction of using a promise that fires after half a second or so. If it fires, the cell yields the number cobbled up so far and starts the egg timer.

As long as you type digits within quick succession (within the half a second), number *= 10 + key.

Two questions:

  1. What is the best way to read from the keyboard and parse its key strokes?
  2. How to best reset the in between key strokes delay?

Tips very welcome. TIA.

Sure, here’s a start:

Collecting keyboard input is the same as it’d be for other JavaScript applications, but the one thing to pay attention to here is focus - because by default people will have the top frame (the Observable website + editor) focused instead of the output cells. So I’ve written a little affordance in this one to hint that people need to click the element to start using the notebook.

Besides that - one Observable’y way to do this would be to have the input as a viewof, and have it return an array of keys typed, and then you can iterate through the array to process changes. This makes it pretty easy to iterate on other cells, because then you’ll be able to tweak the code that turns this stream of user input into numbers and actions without having to re-type the input continuously.

3 Likes

Hi Tom,

Thanks very much! You just jumpstarted me with some clear code.

Martien.

Hi Tom,

As you can see in Martien’s Timer, I’m getting there. I’ve taken your code as inspiration and tweaked it into the simplest version that can possibly work, while meeting my minimum outcome and usability criteria.

However, I’m still struggling with keeping input focus while setting a mutable variable, as demonstrated in Keyboard input.

I must be complicating things or simply missing some basic understanding.

Can you please take a look and assist me in getting unstuck? Thanks.

Got it!

If I say mutable running = !mutable running, the cell does not track (self-)reference, hence does not re-evaluatue, which solves the problem.

Kudos to @kelleyvanevert’s answer on A bit confused about ‘mutable’, etc.