Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate a script X times

I have several functions that may or may not need to be repeated a certain number of times. The number of times is set by the user, and is stored in a variable: xTcount.

if (xTcount > 0) {
    for (i=0; xTcount <= i; i++) {
        $(document).miscfunction();
    }

}

I haven't actually tested the script above, as i'm sure it's incorrect. What makes what i want tricky, is that i don't want to have to code a "check xTcount" clause into every function that is repeatable. if possible, i'd like to create some master checker that simply repeats the next-called function xTcount times...

like image 481
C_K Avatar asked Dec 02 '22 02:12

C_K


1 Answers

Repeat some things xTcount times? Maybe I'm misunderstanding, but it looks pretty simple:

for(var i = 0; i < xTcount; i++) {
    doSomething();
    doSomethingElse();
}

If the trouble is that you don't like the look of the for loop, or that your script requires you to build the same loop multiple times, you could extract it if you reeeaaallllly wanted to:

function repeat(fn, times) {
    for(var i = 0; i < times; i++) fn();
}

repeat(doSomething, xTcount);
// ...later...
repeat(doSomethingElse, xTcount);
like image 181
Matchu Avatar answered Jan 03 '23 00:01

Matchu