From my perspective, the best way to interrupt a computation is with the menu command Evaluation/Abort Evaluation
, or from the keyboard, as described here.
However, if using Button
is desirable for other reasons, delete Method -> "Queued"
so that the "Stop" code is executed immediately. Be aware, though, that Quit[]
terminates the Kernel, losing definitions and the like; see its documentation. Instead, use Interrupt
. In either case , Mathematica will stop responding for several seconds, then beginning responding again. With these changes, your code becomes
Grid[{{Button["Start", {i = 1; While[i < 10, Print[i]; Pause[1]; i++]},
Method -> "Queued"]}, {Button["Stop", Interrupt[]]}}]
Note that Abort[]
is ineffective in the code above.
Addendum
However, if the goal literally is to escape on command from a loop, like that in the test problem, Abort[]
, Break[]
, and a few other functions can be used, depending on the details of the loop. For instance,
Dynamic[break = False]
Grid[{{Button["Start", {i = 1; While[i < 10, If[break == True, Abort[]]; Print[i]; Pause[1];
i++]}, Method -> "Queued"]}, {Button["Stop", Dynamic[break = True]]}}]
The advantage of this approach is that Mathematica does not temporarily become unresponsive when "Stop" is clicked. The disadvantage is that the loop terminates only where If[break == True, Abort[]]
is encountered, although it can be located in multiple places in a large loop. Also, Dynamic
can be temperamental.