Home > Web Front-end > JS Tutorial > body text

Javascript knowledge points you must know: the use of 'single-threaded event-driven'_javascript skills

WBOY
Release: 2016-05-16 17:35:35
Original
1343 people have browsed it
Copy code The code is as follows:

var intervalBody = function(){
console.log(' interval');
}

var startInterval = function(){
setInterval(intervalBody,1000);
}

var timeoutBody = function(){
console.log('timeout');
}

var startTimeout = function(){
setTimeout(timeoutBody,1000);
}

var sleep = function(second){
var current = new Date().setSeconds(new Date().getSeconds() second);
while(new Date() < current){ }
}

startInterval();
startTimeout();
sleep(2);
console.log('sleep once');
sleep(2);
console.log ('sleep again');

Execution result

What happened?

Execution Rule Rule 1

Event-driven single-thread model, all JavaScript code is executed in one thread, and the JavaScript thread takes out one event at a time from the event queue for execution.

Rule 2

In addition to the javascript thread, the host also has timer threads (setInterval and setTimeout will trigger the execution of these two threads), browser event triggering threads (this thread will trigger onclick, onmousemove and other browser events), and AJAX requests Threads; all events (callbacks) triggered by these threads will be added to the end of the event queue.

Rule 3

When the browser loads the HTML document, it will treat all the js code of the current HTML as the first event in the event queue, and events (callbacks) triggered by other threads will be added to the end of the event queue.

Rule 4

The execution time of the callbacks in setTimeout and setInterval must be greater than the number of seconds specified for them.

Browser rendering thread

If the javascript execution thread executes the A event and modifies the DOM during the execution of the A event, these DOM modifications will not be immediately reflected on the interface. Instead, when the A event is completed, the javascript thread will be blocked. At this time, the browser rendering thread will render the modification result of the DOM. After the browser rendering thread completes execution, the javascript thread will continue to run.

Code example

Copy code The code is as follows:

var sleep = function(second) {
var current = new Date().setSeconds(new Date().getSeconds() second);
while(new Date() < current){ }
}

document.body.innerHTML = 'Duan Guangwei';
sleep(5);
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template