Is it possible to abort a while loop when a key is pressed?
Lets say I have this code
t=0; While[t<10!,Print[t];t++]
Is there a way to stop this loop when I press space?
Is there a command like "keypressed"?
Is it possible to abort a while loop when a key is pressed?
Lets say I have this code
t=0; While[t<10!,Print[t];t++]
Is there a way to stop this loop when I press space?
Is there a command like "keypressed"?
EventHandler might do what you want. I'll adapt your example a little to make it more practical. I'll also use a mouse click instead of a key press for this first example as the key press is only active while the output is "focused" and it is hard to select the output long enough to do that.
DynamicModule[{stop = False},
EventHandler[
Dynamic[t],
{"MouseClicked" :> (stop = True)}
] // Print;
t = 0; While[t < 11! && ! stop, t++]
];
This gives you a running computation that stops when the Dynamic output is clicked.
If a key press rather than a mouse click is vital then it seems you will need a static area in the output so that focus is easy to maintain. Here is an example of that using the key x to terminate the computation.
DynamicModule[{stop = False},
EventHandler[
Row[{"(inactive area) ", Dynamic[t]}],
{{"KeyDown", "x"} :> (stop = True)}
] // Print;
t = 0; While[t < 11! && ! stop, t++]
];
Click inside "inactive area" to move the cursor to that location, then press x to terminate.
Alt+., but take a look at CellEventActions and friends if you want. – Kuba Jun 01 '17 at 21:41