Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>however sometimes this function gets called twice at the same time resulting in receiving exactly the same result twice, something I don't want.</p> </blockquote> <p>JavaScript on browsers is single-threaded (barring using the new <a href="http://www.w3.org/TR/workers/" rel="nofollow">web workers</a> stuff, but that wouldn't apply here anyway). Your function will never get called while it's running. (But more below.)</p> <p>In your various code quotes, you're <em>calling</em> <code>myFunc</code> where you mean to just be referring to it. E.g.:</p> <pre><code>var interval = setInterval(myFunc(), 5000); </code></pre> <p>should be</p> <pre><code>var interval = setInterval(myFunc, 5000); // ^--- No parentheses </code></pre> <p>Your code cancelling the timeout will work if you correct that:</p> <pre><code>var interval = setInterval(myFunc, 5000); function buttonClick() { clearTImeout(interval); // do some stuff myFunc(); interval = setInterval(myFunc, 5000); } </code></pre> <p>But there's no reason to do that, <code>myFunc</code> cannot get called while it's running anyway.</p> <p>If <code>myFunc</code> is <em>triggering</em> something that will complete asynchronously (an ajax call, for instance), the above <strong>won't</strong> help (for the simple reason that <code>myFunc</code> will start the process and then return; the process will complete separately). In that situation, your best bet is to have <code>myFunc</code> schedule its next call itself:</p> <pre><code>function myFunc() { // Do my work... // Schedule my next run setTimeout(myFunc, 5000); } </code></pre> <p>...and not use <code>setInterval</code> at all.</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