4
$\begingroup$

Sometimes it can come in handy to set a lower limit for a calculation. Consider for example an animation that is generated by some infinite loop, which would run way too fast to display properly for the user. For this reason, I need a function of the type "pause at least". It would be like a little brother of TimeConstrained.

I threw together the following small code which seems to do the trick, but I'm wondering whether there is a more efficient or elegant solution for this?

Here's my version if you're interested, it's pretty straightforward:

pauseAtLeast[calculation_, pause_] :=
    Block[{start, result},
        start = AbsoluteTime[];
        result = calculation;
        If[AbsoluteTime[] < start + pause,
            Pause[start + pause - AbsoluteTime[]]
        ];
        result
    ]
SetAttributes[pauseAtLeast, HoldFirst];

Usage:

(* Pauses 2 seconds *)
AbsoluteTiming@pauseAtLeast[Pause[2], 1]
(* Pauses 1 second *)
AbsoluteTiming@pauseAtLeast[Pause[.5], 1]
$\endgroup$
  • $\begingroup$ David, I notice that you have Accepted answers to nearly all of your questions, but not this one. An oversight, or was it never answered to your satisfaction? $\endgroup$ – Mr.Wizard Apr 24 '13 at 11:11
  • 1
    $\begingroup$ @Mr.Wizard The answers provided don't really add anything to my naive implementation. When I asked this, I wondered whether maybe there's a built-in function to handle this (plus all possible special cases I could think of). $\endgroup$ – David Apr 24 '13 at 14:52
  • $\begingroup$ I see. Thanks for the clarification. $\endgroup$ – Mr.Wizard Apr 25 '13 at 1:16
2
$\begingroup$

A similar but slightly shorter solution...

SetAttributes[pauseAtLeast2, HoldFirst]; 

pauseAtLeast2[calculation_, pause_] := 
   With[{res = AbsoluteTiming[calculation]},
        If[res[[1]] < pause, 
               Pause[pause - res[[1]]]
        ]; 

        res[[2]]
   ]
$\endgroup$
2
$\begingroup$

Same as Andy but in terse style:

SetAttributes[holdFor, HoldFirst];

holdFor[op_, hold_] :=
  (Pause[# UnitStep@#] &[hold - #]; #2) & @@ AbsoluteTiming @ op
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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