Monday 15 April 2013

javascript - Understanding Threading/Synchronicity Through JS's setTimeout -


Javascript's session timeout function is causing me to re-evaluate me for a little bit about javascript. (; I & lt; length; i ++ i = 0) {setTimeout (executeOtherCode, 5000)}

  For: Before today, Part I for the loop 

I expected that the execution of this code was executed by the other codec function, "sleep" for 5 seconds, and continue with the next frequency. Instead I was executed with the other executing the length of time together.

So by my understanding, setTimeout has an asynchronous function call. is this correct? However, if I was performing a regular function, then we call it a huge function, which takes 1 minute to execute, the next line of code will not be executed until the function has done nothing, right ? So why are two different? Just like a language design?

I have seen other functions in jQuery which behave in an asynchronous way in an equally manner, such as getJSON, is it a matter of knowing which work is defined as asynchronous , Or is there any type of pattern to identify them? If so what? Generally, except special cases - Javascript synchronizes and executes in sequence.

   

setTimeout (executeOtherCode, 5000) < P> is saying "In 5 seconds, run the function executeOtherCode ". This keeps loop running, this 'block' does not execute.

In 5 seconds, the event loop will be set up in a timer (well, length timer) and

if you have a second of 5 seconds If you want to execute the work in delay, you will have to tell the next function to execute 5 seconds after the last task is completed, this pattern is called asynchronous semaphore.

The general rule of thumb is that If it is I / O, this is asynchronous , this is why AJAX is asynchronous (and should also have script tag injection other HTTP Requests) and Interaction Event Asynchronous (Javascript responds to clicks for example, it does not wait for them) Timer (Settemout and Set Interval are also asynchronous)

Everything else is synchronous.

Now, some functions use it these other functions but to find out which is just plain documents. Most asynchronous functions have callback parameters (like the first parameter of ExecutionOutcorp), but nothing does, and some functions accept callback but do not have asynchronous.

No comments:

Post a Comment