How could I create a warning dialog that executes a function if not cancelled after a delay ? Also I would like the time remaining before execution to be displayed and the dialog to be non blocking.
2 Answers
I think this does what you want:
SetAttributes[countdownConfirm, HoldRest]
countdownConfirm[msg_, body_] :=
CreateDialog[
Column[{
Row[{msg, " ",
Dynamic[If[# > 0, #, DialogReturn[body]; #] & @
Ceiling @ Clock[{5, 0}, 5, 1]]}],
CancelButton[]
}]
]
Test:
countdownConfirm["A print will happen in", Print@"A print happened indeed!"]
-
$\begingroup$ Nice, and simpler than me. You get the accept. $\endgroup$– faysouFeb 28, 2016 at 22:05
-
1
-
$\begingroup$ @faysou Thank you, and I'm glad I could help. You're right regarding
Setting
; I don't know why I put that in, other than personal confusion. I also addedDialogReturn[body]; #
because I just noticed a momentary "shudder" in the dialog window before it closes, and this seems to fix it. $\endgroup$ Feb 28, 2016 at 23:52 -
1$\begingroup$ Clock is an interesting function as it manages to update in Dynamic without an explicit symbol to track. There must be a code rewrite behind the scene. $\endgroup$– faysouFeb 29, 2016 at 7:51
-
$\begingroup$ @faysou I've never thought about that. Thanks. $\endgroup$ Feb 29, 2016 at 7:53
Using the function below we can do:
ExecuteIfNotCanceled["A print will happen in",Print@"A print happened indeed!"&]
This function is interesting as it uses many different aspects of Mathematica.
ExecuteIfNotCanceled[message_,function_,delay:_Integer:5]:=
DynamicModule[{n=delay,decrementTask,closeScheduledTask,dialog,tasks},
tasks = {decrementTask,closeScheduledTask};
decrementTask=CreateScheduledTask[n--];
closeScheduledTask=
CreateScheduledTask[
NotebookClose@dialog;
RemoveScheduledTask /@ tasks;
function[];
,
{delay}
];
StartScheduledTask /@ tasks;
dialog=
CreateDialog[
Column[
{
Dynamic[message~~" in "~~ToString@n~~" seconds.",TrackedSymbols:>{n}]
,
CancelButton@DialogReturn[RemoveScheduledTask /@ tasks]
}
,
Alignment -> Right
]
,
Modal->False
];
];