5

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.

faysou
  • 10,999
  • 3
  • 50
  • 125
  • 1
    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

2 Answers2

2

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
            ];
    ];
faysou
  • 10,999
  • 3
  • 50
  • 125
2

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!"]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • Nice, and simpler than me. You get the accept. – faysou Feb 28 '16 at 22:05
  • 1
    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
  • 1
    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 07:51
  • @faysou I've never thought about that. Thanks. – Mr.Wizard Feb 29 '16 at 07:53