It seems that I cannot use a loop in Dynamic. Quite ridiculous??

Here is my minimal example:

Grid[{{Button["test", i = 0; While[i < 10, Pause[10]; i++]], InputField[Dynamic[i]]}}]

I expect the dynamic i will increase by one every ten seconds(10 seconds gap is set to prevent it goes too fast to be observed). But the truth is i just starts from 0 and stops when I click on the button.

Thanks for your attention! Any comments and suggestion will be very welcome.

Edit: Thanks to comments from Kuba, I am now able to let the button update the value of i in a loop, but it still fails to work if I put them in DynamicsModule after check some other related questions.

The minimal example is:

DynamicModule[{i = 0},  Grid[{{Button["test", i = 0; 
 While[i < 10, i++; Pause[1]; FinishDynamic[]], 
 Method -> "Queued"], 
InputField[Dynamic[i, UpdateInterval -> .5]]}}]]
  • 2
    $\begingroup$ This will work: Button["test", i = 0; While[i < 10, Pause[1]; i++; FinishDynamic[]], Method -> "Queued"]. Method is a must and FinishDynamic[] is a remedy for this bug: 100828 $\endgroup$
    – Kuba
    Jul 27, 2017 at 10:03
  • $\begingroup$ Do you mean this 'feature' is a known bug in Mathematica 11.1? @ Kuba♦ $\endgroup$
    – Jake Pan
    Jul 27, 2017 at 10:04
  • 2
    $\begingroup$ The point is that preemptive evaluation locks the front end so InputField won't be updated before whole loop finishes. $\endgroup$
    – Kuba
    Jul 27, 2017 at 10:06
  • $\begingroup$ Thanks! I see it now. Because 'Button' will time out after 5 seconds by default. What a hidden pitfall! $\endgroup$
    – Jake Pan
    Jul 27, 2017 at 10:08
  • $\begingroup$ further reading: 59949, 5356 $\endgroup$
    – Kuba
    Jul 27, 2017 at 10:09


Browse other questions tagged or ask your own question.