Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Geoff has outlined one approach (using <code>setInterval</code> and clearing it from the callback), so I'll outline the other: Using <code>setTimeout</code> from the callback. Something like</p> <pre><code>m = 10 do drawCallback = -&gt; draw m, 150 m += 10 setTimeout drawCallback, 1000 unless m &gt; 100 </code></pre> <p>Note that there is a subtle timing difference between the two approaches that you should be aware of: <code>setInterval func, 1000</code> will run the function once every 1000ms; the chained <code>setTimeout</code> will put a 1000ms delay between each function call. So if <code>draw</code> took 100ms, say, the chained <code>setTimeout</code> would be equivalent to <code>setInterval func, 1100</code>. It probably doesn't matter, but it's worth being aware of.</p> <p><strong>Bonus approach</strong>: You don't <em>have</em> to abandon your loop; you could just set all the timeouts from it at once:</p> <pre><code>for m in [10..100] by 10 do (m) -&gt; setTimeout (-&gt; draw(m, 150)), 100 * m </code></pre> <p>The <code>do (m)</code> is necessary so that the closure passed to <code>setTimeout</code> sees each value of <code>m</code>, not just its final value in the loop. See my article <a href="http://pragprog.com/magazines/2011-05/a-coffeescript-intervention" rel="noreferrer">A CoffeeScript Intervention</a> for more info on this.</p> <p><strong>Finally</strong>: I know this all seems very confusing at first, but timing in JS is actually very simple because the language is single-threaded. That means that events you schedule with <code>setTimeout</code> or <code>setInterval</code> or any other async function will never occur <em>during</em> a loop, even if the loop is infinite. They only occur after all of your code has finished executing. I talk about this in a little more detail in <a href="http://pragprog.com/book/tbcoffee/coffeescript" rel="noreferrer">my book on CoffeeScript</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload