The sea is wide by diving, the sky is high as birds fly. Hey how are you! I’m Ed Qin. πŸ˜„

takeaway

Just before The National Day, a colleague wrote a drag-and-drop menu bar on the left to change the width of the menu bar to get a better interactive experience. But!!! The fly in the ointment is that if you drag too fast, it will cause the lag effect and look very uncomfortable. After continuous debugging, setTimeout was finally used to solve the problem. So here’s the problem! Why does setTimeout solve animation stutter?

A picture is worth thousands of words, through the two pictures before and after comparison, let’s see the actual effect!

(This is without adding setTimeout before there is a noticeable lag πŸ˜”πŸ˜”πŸ˜”)

(this is after adding setTimeout, the drag effect is significantly smoother 😁😁😁)

Hypothetical question: Could there be too much content? 😲

To confirm my conjecture, I switched to fewer modules.

Sure enough, the drag effect immediately smooth a lot πŸ˜†πŸ˜†πŸ˜†

At this time, it can be basically confirmed that the content is too much caused by the lag, then how to ensure that the content does not change the size of the situation to achieve smooth drag effect?

Propose a solution: Can drag be smooth by reducing backflow times to save performance? 😲

For this reason, the content on the right has a fixed width. When dragging and dropping the menu, since the width of the content on the right has been fixed, the size of the element box will not change, so it will not trigger backflow.

Sure enough, the drag effect is much smoother again πŸ˜†πŸ˜†πŸ˜†

What is reflux and redraw?

Backflow: When we make changes to the DOM that result in a change in the DOM’s geometry (such as changing the width or height of an element, or hiding an element), the browser recalculates the element’s geometry (which also affects the geometry and position of other elements), and then draws the calculated results. This process is called backflow (also known as rearrangement).

Redraw: When we make changes to the DOM that result in a style change without affecting its geometry (such as changing the color or background color), the browser doesn’t have to recalculate the element’s geometry and simply draw a new style for the element. This process is called redrawing.

Redrawing does not necessarily lead to backflow, backflow does lead to redrawing!

Reducing backflow by controlling content width does solve the lag problem, but it makes the page unadaptable to all screen sizes. Is there a way to solve the menu drag problem without changing either the content size or the content box size?

Can drag and drop be smoothed by shuffling the module declaration cycle and changing the order in which tasks are executed? 😲

As the title shows, when we put the code to change the size of the element into setTimeout. Use setTimeout to achieve a pseudo-multithreading effect, thus solving the drag problem!

About this, the backside knowledge that involves is still very much, mo panic! Please continue to read πŸ‘‡πŸ‘‡πŸ‘‡

Browser Rendering process (Brief description)

When we enter the url in the browser to render the page, we generally go through three steps at the browser rendering level (download πŸ‘‰ parse πŸ‘‰ layout) :

1: sends a request to the server based on the page URL, and the server responds with the HTML of the page. The browser first downloads HTML, JS, CSS, images, fonts and a series of resources.

2: Browsers parse HTML into a DOM tree and CSS into a rule tree, combining the two into a render tree.

3: After the rendering tree is built, the browser’s rendering engine will walk through the tree and draw each node to render the page as we see it.

The browser refresh rate is about 60 times per second, which means a refresh time is about 16ms. If the browser works on each frame longer than that, the page’s rendering will stagnate.

Browser Processes and Threads (Brief Description)

We all know that JavaScript is single-threaded, but browsers support multiple processes. So, with the proper allocation of the browser, each process does its job and has a lot of fun.

What is a process?

A process is the basic unit of CPU resource allocation

What is a thread?

A thread is the smallest unit of CPU scheduling. It is a unit that runs on the basis of a process and shares its memory space.

What processes are included in the browser?

1: browser process (responsible for browser-level operations, such as TAB page creation and destruction, resource management and download, etc.)

2: Third-party plug-in process (responsible for the use of third-party plug-ins)

3: GPU process (responsible for 3D drawing and hardware acceleration)

4: browser rendering process (browser kernel is responsible for parsing and executing HTML, CSS, JS and other files)

The browser rendering process (browser kernel)

The browser rendering process consists of five main threads:

1: GUI rendering thread

2: JS engine thread

3: timer thread

4: The timer triggers the thread

5: Asynchronous Http request threads

The GUI rendering thread and the JS engine thread are mutually exclusive, as they cannot run simultaneously. Imagine that the render thread is rendering the background color of a div, and the JS engine thread is trying to change the background color and size of your div element with JS. So which side is the standard at this time. It has to be a mess. So, while either thread is executing, the other thread’s operation is suspended, waiting for the other tasks to complete, and then coming back to execute this task.

With this knowledge behind us, we need to take a look at macro tasks and micro tasks, as well as event loops and task queues. I won’t go into too much detail here, but read a very good article by Jiasm! Portal – Here you go πŸš€πŸš€πŸš€

About the setTimeout

The setTimeout function is used to specify how many milliseconds after a function or piece of code will be executed.

SetTimeout will remove the specified code from the current execution and wait for the next Event Loop to check whether the specified time is reached. If so, execute the corresponding code; If not, wait until the next round of Event Loop to judge again. This means that the code specified by setTimeout will not be executed until all code has been executed.

SetTimeout literacy:

1: The this keyword in setTimeout will point to the global environment, not the object at which it was defined.

2: setTimeout is an asynchronous task and a macro task. So it was the last mission to be executed.

3: setTimeout Indicates the length of the callback interval

setTimeout( () =>{ console.log('hello'); }, 100).Copy the code

Note: The time interval here must be greater than 100ms, depending on how much time it takes to synchronize the JS execution of the task before then.

4: Difference between setTimeout(func,0) and setTimeout(func)

SetTimeout (func,0) : Suspends the func callback function until all synchronization tasks and tasks in the task queue are completed. In fact, 0 milliseconds is not actually possible. SetTimeout Specifies the time to delay execution. The value must be at least 4 milliseconds.

SetTimeout (func) : If no specific delay is passed, the browser automatically allocates time to the timer. The amount of time allocated varies from browser to browser.

5: What is the maximum delay time of setTimeout?

The answer is: 2147483647 milliseconds (24.8 days). Any time beyond this will be treated as an overflow, equivalent to setTimeout(f,0).

6: setTimeout will return an integer value representing the counter number. Pass this integer into clearTimeout to cancel the corresponding timer.

————– gorgeous dividing line ————–

Qin Ed you said so much, this with drag carden have what relation? 🌚 🌚 🌚

Ha ha, you don’t panic, let’s go step by step, next I will introduce you to a wave of setTimeout practical use! 🌝 🌝 🌝

Purpose: Adjust the sequence of events

setTimeout( () =>{
  console.log(2);
},0)
console.log(1);
Copy the code

We all know that JS parses code line by line and only suspends asynchronous tasks after synchronous ones. So we take advantage of this feature to shuffle the order of events to meet a particular requirement scenario.

Purpose 2: Split time-consuming tasks

We all know that javascript is single-threaded and prone to blocking. If a program takes too long to process, the entire page can easily get stuck. If you can’t do anything else, you can solve this problem by using setTimeout to split the tasks.

Use drag to change the width of an element for example 🌰

. Document. onmousemove = function (e) {... SetTimeout (() =>{document.getelementById ("app").style.width = XXX + 'px'},0)}Copy the code

As shown in the code above, we frequently trigger backflow while dragging and dropping elements, which in itself is very expensive. This time it is very easy to appear blocking, resulting in a web page stuck. At this time, we add setTimeout to skillfully divide this part of the operation. The task is executed in the earliest available idle period of the browser. Those tasks with large computation and long time are executed in setTimeout(f,0) respectively (fragments are queued), so that even if the complex program is not finished processing, When we operate the page, we get an immediate response.

Purpose three: event anti – shake and throttling

About this part of the content, if want to elaborate again is long, here directly recommended reading little dot don’t play I write very good article portal – go you πŸš€πŸš€πŸš€

All right! This is a brief introduction to the exploration of setTimeOut caused by a drag and drop stuck problem. It can be seen that a small problem also needs strong theoretical knowledge support. So, master some of the basic principle of JS knowledge, is our ability to promote personal, into the next stage of the key step. Here’s one of my favorite amway quotes:

80 percent of the problems can be solved with 20 percent of your knowledge, and the remaining 20 percent needs to be solved with 80 percent of your knowledge.

Scatter flowers 🌸🌸🌸🌸 disk 🌸🌸

Click like πŸ‘ to see again, has become a habit! This series is constantly updated, and your one-key three-link is the biggest motivation for me to continue writing. If you have any comments and suggestions on this blog, welcome to leave a message! Welcome to disturb! 😜 😝

I am Qin Aide, a programmer in the Internet to survive!