title: Obj-C, NSTimer Schedule in a loop, correct pattern?
body: <p>I have a completion handler (which evaluates javascript in a web view), inside that I call a NSTimer, I’ve wrapped this up into a function…</p>
  
  <pre><code>-(void)runJSAndGoto: (WKWebView*)web
                   js: (NSString*)js
             selector: (SEL)aSelector
             position: (NSString*)position
          wait_period: (double)wait_period
            user_info: (id)user_info
  {
  
      [web evaluateJavaScript:js completionHandler:^(id result, NSError * error) {
  
          [NSTimer scheduledTimerWithTimeInterval: wait_period
                                           target: self
                                         selector: aSelector
                                         userInfo: user_info
                                          repeats: NO;
          if(error)
          {
              NSLog(@"\n\n%@ error \n%@\n", position, error.description);
          }
      }];
  }
  </code></pre>
  
  <p>So I can call different bits of javascript and on completion do another function, perhaps call some more javascript etc.</p>
  
  <p>OK, here's my issue...</p>
  
  <p>Later I call this function in a loop, which in turn runs a couple of other javascript calls on completion.</p>
  
  <ul>
  <li>loop start</li>
  <li><ul>
  <li>first js call</li>
  </ul></li>
  <li><ul>
  <li><ul>
  <li>first js completes, wait 2 seconds</li>
  </ul></li>
  </ul></li>
  <li><ul>
  <li><ul>
  <li><ul>
  <li>second js call</li>
  </ul></li>
  </ul></li>
  </ul></li>
  </ul>
  
  <p>You can see where I’m going with this. Basically, the first call in the loop runs a lot (up until the first wait period) and so on. It’s a bit of a mess.</p>
  
  <ul>
  <li>loop start</li>
  <li><ul>
  <li>first call</li>
  </ul></li>
  <li><ul>
  <li>first call</li>
  </ul></li>
  <li><ul>
  <li>first call etc until 2 seconds has passed</li>
  </ul></li>
  <li><ul>
  <li><ul>
  <li>second call</li>
  </ul></li>
  </ul></li>
  </ul>
  
  <p>I want the full “stack” to complete before the next loop iteration starts.
  I'm writing a mac app.</p>