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:


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:


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 1

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

enter image description here

  • $\begingroup$ 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. $\endgroup$ Commented Nov 20, 2017 at 16:44

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.