4
$\begingroup$

It looks like a basic issue but I haven't found an answer anywhere.

Please tell me why the behavior (after clicking) of this Button:

Button["X", Print@1; Pause@1; Print@2;]
    (*1 and 2 appear simultaneously after 1 sec*)

is different from the behavior of Shift+Enter evaluation:

Print@1; Pause@1; Print@2;
    (*printing of 2 happens 1sec after 1*)
$\endgroup$

1 Answer 1

11
$\begingroup$

The reason is because Button actions are calculated on a preemptive link, meaning they preempt any other evaluation, but are only allowed a certain amount of time to evaluate. That indicates:

the front end sends one evaluation at a time and waits for the result before continuing with its other work

So it can't display 1 because it is waiting for Pause[1];Print[2] to finish.

You can replicate the behavior of

Print@1; Pause@1; Print@2;

by adding the option Method->"Queued" to the Button arguments.

This ensures the actions are performed in the current queue and no time limit is enforced.

See the documentation under "Details and Options"


Further reading:

$\endgroup$
2
  • 6
    $\begingroup$ A little more explanation to the OP: Most likely, the code that needs to be run for the new cells to be created and formatted needs to wait until the preemptive evaluation has finished. This is why 1 and 2 seems to appear simultaneously after a pause of 1 second. $\endgroup$
    – Szabolcs
    Feb 13, 2013 at 20:16
  • $\begingroup$ @Szabolcs Thanks for the added color. $\endgroup$
    – kale
    Feb 13, 2013 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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