# Creating a warning before executing a function if not cancelled?

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.

• Here's something very similar: 78017. P.s. keep in mind that using DM variables in ScheduledTasks may be tricky unless you are paying attention: 38291 – Kuba Feb 28 '16 at 10:04

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!"]

• Nice, and simpler than me. You get the accept. – faysou Feb 28 '16 at 22:05
• I don't think you need to use Setting. – faysou Feb 28 '16 at 22:18
• @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 added DialogReturn[body]; # because I just noticed a momentary "shudder" in the dialog window before it closes, and this seems to fix it. – Mr.Wizard Feb 28 '16 at 23:52
• 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. – faysou Feb 29 '16 at 7:51
• @faysou I've never thought about that. Thanks. – Mr.Wizard Feb 29 '16 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]:=

NotebookClose@dialog;
function[];
,
{delay}
];

dialog=
CreateDialog[
Column[
{
Dynamic[message~~" in "~~ToString@n~~" seconds.",TrackedSymbols:>{n}]
,