# Use of timing system to change input variable in a function

Assume you have some function which is defined by a while loop:

sampleFunc[start_] := Module[{i},
While[i = 1; start < 10, i++];]


And let's assume I do:

sampleFunc[5]


This will clearly generate an infinite loop. Thus, for my purposes, say I would like then to increase the starting value by 1 whenever the time taken for sampleFunc exceeds 2 seconds. I continuously do this until sampleFunc completes its evaluation under 2 seconds. Something like:

While[timeTaken[sampleFunc[s]]>2,s=s-1]


Things like TimeConstrained abort the evaluation, whereas I don't want to abort the entire program. I just want to abort the sampleFunc part, change the variable and then reevaluate sampleFunc until it's evaluation time is less than 2 sec.

I know sampleFunc is extremely simplistic and usless, but it serves the purpose I need in order to apply it to a much more complex function.

## 1 Answer

foo[n_] := If[n < 10, While[True], "done"] (*instead of your sampleFunc*)


You don't need to abort, there is a third argument for TimeConstrained:

n = 1;
While[TimeConstrained[res = foo[n], .5, True], Echo[n++]]
res


• I thought I had looked at the extra arguments for TimeConstrained. I guess I didn't understand it correctly. But thanks, it's just how I needed it. – Luca Pontiggia Nov 20 '17 at 16:44