Background:

1. Data display page with an automatic refresh function, so that users can see the latest data. 2. Add a time period and execute it after * (time period) to achieve xx effect. 3. Adjust the execution sequence of these event responses, etc...Copy the code

Timers are often used during development to fulfill certain requirements. Js has two functions for us: setTimeout and setInterval, which we’ll cover briefly before we get into the subject

1. SetTimeout: var timerId =setTimeout(function() {/ /do    
},delay)

2.setInterval
var timerId2 = setInterval(function() {
    //do}, delay) // Delay time periodCopy the code

First, they all return an integer number that identifies the timer. Passing this value to the respective clear methods cancels the timing.

Second, setTimeout is expected to execute a function after ms delay, setInterval is expected to execute a function after ms delay.

Why just say expect that? Go to 🌰

var start_date = 0;
setTimeout(function(){
	var end_date = new Date().getTime()/1000
	console.log('enter setTimeout date : ' +  end_date)
	console.log('time interval : '  + (end_date - start_date) + '秒')
},1000)
function bulky(){
	start_date = new Date().getTime()/1000;
	console.log("bulky start date : " + start_date)
	for(var i=0; i<100000; i++){for(var j=0; j<100000; j++){ var k = 0; k = k*k; } } } bulky()Copy the code

Run the code to predict the result, which looks like this:

How is the timer implemented timing? Why does it happen at irregular times?

First, let’s be clear: javascript runs in a single-threaded fashion. The primary purpose of JavaScript is to interact with users and manipulate the DOM. In a multithreaded manner, conflicts can occur. If you have two threads working on a DOM element at the same time, and thread 1 requires the browser to remove the DOM while thread 2 requires the browser to modify the DOM style, the browser cannot decide which thread to use. Of course, we could introduce a mechanism for “locking” the browser to resolve these conflicts, but the complexity is so great that JavaScript has been single-threaded since its birth. Only one specific task can be executed at a time, and other tasks can be blocked.

But JavaScript has a model based on “Event Loop” concurrency (not parallelism). The former is logical simultaneity, while the latter is physical simultaneity. Therefore, single-core processors can also achieve concurrency.

The figure above illustrates concurrency and parallelism:

The Event Loop is illustrated above

Js is single-threaded, which means that all tasks need to be queued. All tasks can be categorized into two types, synchronous and asynchronous

  • A synchronous task is a task that is queued to be executed on the main thread until the execution of the previous task is completed, forming an execution context stack.

  • Asynchronous tasks are tasks that do not enter the main thread but enter the “task queue”. A task queue is a queue of events (thought of as a queue of messages). When an IO device completes a task or an asynchronous task has a result, it adds an event to the “task queue”, indicating that the relevant operation can be entered into the “execution stack”, waiting for the execution stack to call.

See the Event Loop diagram for an overview of the flow —-> Stream execution functions in the execution stack (synchronous tasks), which may call the API to add events (onlick, onload, etc.) to the task queue but do not execute. The task queue is added to the execution stack only when there are no other operations on the current execution stack

Principle done, back to the main point. Because setTimeout and setInterval are asynchronous tasks, they do not enter the execution stack directly after being called, but enter the task queue. Therefore, they will enter the execution stack only when there is no other operation in the current execution stack. That is why timers are not always timed.

Oh, and if the delay period is set to 0, it’s equivalent to a queue-jumping operation

For example,

🌰 offer:

function f1(){
	console.log('f1')}function f2(){
	console.log('f2')}function f3(){
	console.log('f3')
	setTimeout(function(){
		console.log('setTimeout1'}}, 2000)setTimeout(function(){
	console.log('setTimeout2')
},3000)
setTimeout(function(){
	console.log('setTimeout3')
},1000)
setTimeout(function(){
	console.log('setTimeout4')
},0)

f1()
f2()
f3()
Copy the code

The results

Well, the above content is my understanding of JS timer, I hope to help you

Shall not be reproduced without my permission. There are omissions and superficial articles, please correct them