fletchervk
fletchervk

Reputation: 3

html5 and javascript: is setTimeout breaking this?

I am confused as to why the following html is not working. I would expect it to keep sending alerts but it stops after one. Furthermore, the "left fn" alert never occurs! Can anyone explain this to me? I am using html5 with javascript in firefox on ubuntu.

<!DOCTYPE html>
   <script>
      function alertme() {
      alert ("in fn");
      }

      while (true) {
       window.setTimeout(alertme(), 3000);
   alert("left fn");
      }
   </script>

Upvotes: 0

Views: 302

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123513

A few probable issues:

  1. alertme() is being called immediately and its return value is instead being passed to setTimeout().

    To fix this, you can pass alertme as a reference (without the calling parenthesis):

    setTimeout(alertme, 3000);
    
  2. However, this will then conflict with JavaScript's (primarily) single-threaded nature.

    The setTimeout()s, being asynchronous, simply start a timer that expires no less than 3 seconds from now. But, they require that the one thread is eventually not busy for the delayed task to be performed.

    However, the while (true) {}, being synchronous and indefinite, will keep the thread busy until all execution is stopped and will never allow the timeouts to perform their tasks. So, you will never see "in fn".

    John Resig has a good write up on timers: http://ejohn.org/blog/how-javascript-timers-work/

How exactly to fix the code depends on the intent.

Upvotes: 2

El Hocko
El Hocko

Reputation: 2606

while (true) {
    window.setTimeout(alertme, 3000); //setTimeout wants a function, not the return value of the function
    alert("left fn");
}

btw, have fun with klicking all the messageboxes away...

Upvotes: 2

Related Questions