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

**URL:** <https://discourse.julialang.org/t/elegant-way-to-initiate-a-loop-once-a-condition-is-met-and-then-check-the-condition-holds-every-nth-iteration/95751>\
**Category:** New to Julia\
**Tags:** question, loops\
**Created:** [March 8, 2023, 5:15pm UTC](https://discourse.julialang.org/t/elegant-way-to-initiate-a-loop-once-a-condition-is-met-and-then-check-the-condition-holds-every-nth-iteration/95751 "2023-03-08T17:15:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![phantom](https://avatars.discourse-cdn.com/v4/letter/p/e0b2c6/32.png) [@phantom](https://discourse.julialang.org/u/phantom)\
**Post date:** [March 8, 2023, 5:15pm UTC](https://discourse.julialang.org/t/elegant-way-to-initiate-a-loop-once-a-condition-is-met-and-then-check-the-condition-holds-every-nth-iteration/95751/1 "2023-03-08T17:15:30Z")

</div>

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.

```julia
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.

```julia
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!

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://discourse.julialang.org/u/jules)\
**Post date:** [March 8, 2023, 6:05pm UTC](https://discourse.julialang.org/t/elegant-way-to-initiate-a-loop-once-a-condition-is-met-and-then-check-the-condition-holds-every-nth-iteration/95751/2 "2023-03-08T18:05:55Z")

</div>

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