# Setting a lower limit on calculation time

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]

-
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? – Mr.Wizard Apr 24 '13 at 11:11
@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). – David Apr 24 '13 at 14:52
I see. Thanks for the clarification. – Mr.Wizard Apr 25 '13 at 1:16

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

-

Same as Andy but in terse style:

SetAttributes[holdFor, HoldFirst];

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

-