Elegant way to initiate a loop once a condition is met and then check the condition holds every nth iteration

Suppose I have a function that initiates a loop when a condition is met and then checks back on the condition every nth iteration.

(note: Condition does NOT have to hold for iterations 2 : (n-1) ) e.g.

function fun (stuff, start, n)
    # check condition to initiate loop
    (Dates.Time(Dates.now()) > start) || sleep(# until start)
    for (i, x) in enumerate(Iterators.cycle(stuff))
        # do stuff   
        if i % n == 0 
            # check condition again to make sure for n+1 
            Dates.Time(Dates.now()) > Start || sleep(# until start)
        end 
    end
end     

Here the same condition test is in the code twice which seems verbose. Is this bad practice and is there a better way to approach this? If I move the condition to the front of the loop, i.e.

function fun (stuff, start, n)
    for (i,x) in enumerate(Iterators.cycle(stuff))
        if (i % n == 0) || (i == 1)
            Dates.Time(Dates.now()) > start || sleep(# until start)
        end 
        # do stuff 
    end
end   

I introduce an additional test on every iteration which also seems suboptimal. I suspect Iā€™m missing something simple so just wondering if there was a smarter way to go about this with a for loop, thanks!

If you want every nth iteration after the first one, maybe do if i % n == 1?

2 Likes