On the operation mechanism of JavaScript from settimeout

Source: Internet
Author: User
Tags date count execution log setinterval sleep function string thread

Objective


Recently looking at some JavaScript asynchronous things, but due to limited time, just look at the beginning, had to stop halfway. In order to facilitate the future of the search for a return, it recorded a little experience, if it can make others gain, it is very good. In fact, this article and asynchronous does not have much relationship.
From SetTimeout.

As we all know, JavaScript is a single-threaded programming, what is single-threaded, that is, the same time JavaScript can only execute a piece of code, if the code to perform a long time, then the code can only wait for it to execute the opportunity to execute, unlike people, people are multi-threaded, So you can watch an island action movie, while the sweat. JavaScript single-threaded mechanism is also forced, assuming that there are multiple threads, while modifying a DOM element, then what is the thread to listen to?

Now that JavaScript is a single-threaded language, it's understandable that we're trying to figure out the asynchronous approach to JavaScript. such as execution to a piece of code, the requirement is 1000ms after the call method A,javascript No sleep function can suspend the thread a second ah? How can you make the code wait for the A method to execute while continuing to execute the following code as if it were two threads in general? Mechanism scientists have come up with the SetTimeout method.

SetTimeout method Presumably everyone is already familiar with, then settimeout (function () {..}, a) really is to perform the corresponding callback after AMS?

settimeout (function () {
Console.log ("Hello World");
}, 1000);

while (true) {};

In 1s, the console did not output the string as expected, and the circle on the page label kept turning, pinching, and possibly falling into the dead loop of while (true) {}, but why? Although it will fall into the cycle of death, but also first output string Ah! This is going to be about the JavaScript running mechanism.


JavaScript operating mechanism

How exactly does a piece of JavaScript code execute? Nanyi teacher has a good article (JavaScript operation mechanism Detailed: Talk about the event Loop), I will not repeat the wheel, if it is too long to see, the landlord briefly vernacular description. A section of JS code (which may contain some settimeout, mouse clicks, Ajax and other events), from top to bottom to start execution, encounter settimeout, mouse clicks and other events, asynchronous execution of them, this time will not affect the code body to continue to execute, once the asynchronous event is completed, the callback function Go back and add them sequentially to the execution queue, and note that if the principal code is not executed, it will never trigger the callback , which is why the above code causes the browser to suspend animation (while (true) in the principal code {} Not finished yet).

There is also a very popular article on the Internet (poke how JavaScript timers Work), the article has a good picture, I stole it over.

There is no code for this picture, and in order to better illustrate the process, I try to give the code:

Some code

settimeout (function () {
console.log ("Hello");

Some code

document.getElementById ("BTN"). Click ();

Some code

setinterval (function () {
console.log ("World");

Some code

We start executing the code. The first piece of code probably executes 18ms, that is, JavaScript's main code, in the execution process, first triggered a settimeout function, the code continues to execute, only after 10ms response to SetTimeout callback, followed by a mouse click event, The event had a callback (perhaps something in alert) that could not be executed immediately (single-threaded) because the JS principal code was not finished, so the callback was inserted into the execution queue and waited for execution; then the SetInterval function was executed, and we knew that every 10ms would A callback (attempt) is inserted into the queue, and the callback of the SetTimeout function is inserted into the queue when it is run to the first 10ms. JS function after the main run, probably 18ms this point, we found that there is a click in the queue callback, there is a settimeout callback, so we first run the former, in the process of operation, SetInterval 10ms response time also passed , the same callback is inserted into the queue. Click the callback run, run SetTimeout callback, then 10ms passed, SetInterval again produced a callback, but this callback was abandoned, after what happened to everyone at a glance.

One thing I don't quite understand here is the drop on the interval callback. According to how JavaScript timers work, if the wait queue has a callback for the same interval function, there will be no same callback inserted into the wait queue.

Found a predecessor's article JavaScript Timer learning notes, which said "to ensure that the timer code inserted into the queue for the minimum interval of a specified time." When using SetInterval (), the timer code can be added to the code queue only if there is no other code instance for the timer. But I did it myself and thought it might not be so:

var starttime = +new Date;
var count = 0;
var handle = setinterval (function () {
console.log ("Hello World");
count++;
if (count = = 1000) clearinterval (handle);

while (+new Date-starttime < 10 * 1000) {};

According to the above, the same setinterval callback cannot be added to the wait queue because of the "blocking" of the thread, but the actual console in Chrome and FF outputs 1000 Hello World strings. I also went to the original blogger article under the message inquiry, for the time being did not reply to me, but also may be my knowledge of the setinterval posture is not caused, if you know the friend also hope that the generous enlighten, extremely grateful!

In short, the timer simply adds code to the code queue at some point in the future, and execution time is not guaranteed.

SetTimeout VS setinterval

Have seen this before, setinterval function can be used settimeout to achieve, think about, and endless recursive call settimeout is setinterval it?

SetInterval (function () {   //some code
}, 10);

According to the previous description, we probably understand the execution time difference of the above setinterval callback function <=10ms, because the thread blocking can cause a series of callbacks to be queued. What is the setinterval effect achieved with settimeout?

1
function func () {
settimeout (function () {
//Some code
func ();
}, ten);

Func ();


2
settimeout (function () {
//some code
settimeout (Arguments.callee, 1000);
}, 10);

Obviously, the interval between the two callbacks is >10ms, because the previous callback is queued in the queue, and if not, the following callback is not performed, and >10ms is because the code in the callback has to execute the time. In other words, the setinterval callback is tied, the previous callback (with no execution) does not affect the latter callback (the insertion queue), and the callback between the settimeout is nested, and the latter callback is the callback of the previous callback (a bit of tongue twisters mean)



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.