8
$\begingroup$

I dug around a bit and did not find a simple and clear implementation of countdown stopwatch in Mathematica. I am looking for a function that takes as an input a certain integer and then counts down by 1 every second till 0 is reached. I think it could be an important part for some examples. Kernel or Front End implementations are both acceptable. Here is my take on it:

timer[s_] := Module[{x = AbsoluteTime[], y = AbsoluteTime[]}, 
              RunScheduledTask[y = AbsoluteTime[], {1, s}];
              Dynamic[s - Floor[y - x]]]

It's a bit hacky but works ;-) I have seen the following questions already:

but I do not think they do what I was looking for. They either run time forward, are too complex, or something else. Did I miss anything? Does anyone have better ideas?

$\endgroup$

1 Answer 1

14
$\begingroup$

What about

timer[s_] := Dynamic[s - Clock[{0, s, 1}, s, 1]]
$\endgroup$
6
  • 1
    $\begingroup$ +1 Very nice ;) I wonder if there are any other solutions. $\endgroup$ Jul 22, 2012 at 2:32
  • 1
    $\begingroup$ @Rojo Anolther question, but... is it possible to forse Mathematica to play a sound when 0 is reached? $\endgroup$ Jul 22, 2012 at 6:36
  • 2
    $\begingroup$ @AlexeyPopkov it seems like Clock updates one extra time when it stops. But we can always do timer[s_] := DynamicModule[{guard = True}, Dynamic[ If[guard && # === 0, Beep[]; guard = False; #, #] &[ s - Clock[{0, s, 1}, s, 1]]]] $\endgroup$
    – Rojo
    Jul 22, 2012 at 12:09
  • $\begingroup$ @Rojo how can we make this work so that it does two things: (Beep[];NotebookSave[])&? $\endgroup$ Aug 18, 2021 at 12:10
  • 1
    $\begingroup$ @Rojo nevermind to questions in previous comment. i figured it by digging into the documentation. $\endgroup$ Aug 29, 2021 at 23:14

Your Answer

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

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