0
$\begingroup$

Suppose I use a Button[] to make some event occur, how can I make the pressing of this button keep that event occurring at a controlled rate? I tried the following:

x = 0;
Button["X", Dynamic[Refresh[x = x + 1, UpdateInterval -> 1]]]
Dynamic[x]

But it doesn't keep repeating the event x=x+1 if the button keeps pressed. If there is some neater/better alternative without Button[], I'm open to it.

$\endgroup$
0

1 Answer 1

2
$\begingroup$

Here is one way to control the rate using a Checkbox control.

Clear[delay, dt, flag, prev, x]
dt = 1;
flag = False;
prev = AbsoluteTime[] ;
x = 0;
delay := If[AbsoluteTime[] >= prev + dt && flag,
    prev = AbsoluteTime[]; True,
    False]
Row[{Checkbox[Dynamic[flag]], " Click to run"}] // Framed
Dynamic[Refresh[If[delay, x = x + 1, x], UpdateInterval -> 1]]

There are other controls besides Checkbox that might do a better job. The timing could also be improved. The counter is immediately updated as soon as it is clicked on. Maybe it should wait 1 second. Then, it seems to wait an extra second before it starts regular counting.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.