Detailed explanation of javascript advanced timer_javascript skills
setTimeout() and setInterval() can be used to create timers, and their basic usage will not be introduced here. Here we mainly introduce the code queue of javascript. No code in JavaScript is executed immediately, it is executed as soon as the process is idle. Therefore, the time set in the timer does not mean that the execution time must match, but it means that the code will be added to the queue to wait after the specified time interval. If there is nothing else in the queue at this point in time, then this code will be executed, and it will appear as if the code was executed at the precisely specified point in time. So some problems will arise.
Repeat timer
Usually, we use the setInterval method to repeatedly execute a certain piece of code at the same time interval. But there are two problems with using this method: the first is that some intervals will be skipped; the second is that the interval between code executions for multiple timers may be smaller than expected.
Here, let's take an example: If an onclick event handler uses setInterval to set a repeating timer with a 200ms interval, if the event handler takes 300ms to complete, it will skip a time interval and run an timer code.
We can also get the conclusion through the following code:
//重复定时器 var i =0; setInterval(function(){ //如果事件处理时间长于间隔时间 i++; for(var j=0;j<100000000;j++){} document.write(i+' '); },100); //可以明显感觉到时间间隔不相等 为了避免这种时间间隔的问题,我们可以采用链式调用setTimeout方法来取代setInterval。 //可以采用链式调用setTimeout来取代setInterval var i = 0; setTimeout(function(){ //处理内容 i++; for(var j=0;j<100000000;j++){} document.write(i+' '); // setTimeout(arguments.callee,100); },100); //这样处理效果明显好多了。
A new timer is created every time the function is executed. The second setTimeout call uses arguments.callee to obtain a reference to the currently executed function and set another timer for it. This is done so that no new timer code will be inserted into the queue until the previous timer code is executed, ensuring that there will not be any missing intervals and that at least the specified time will be waited before the next timer code is executed. intervals to avoid continuous runs. It can be said that it kills two birds with one stone. Nowadays, animations in mainstream frameworks generally implement repeated timing in this way.
Function throttling
The timer is not only used for timing, but can also be used to relieve the pressure on the browser. Some calculations and processing in the browser are much more expensive than others. For example, DOM operations require more memory and CPU time. Continuous use of too many DOM operations may cause the browser to hang or even crash.
The basic idea of function throttling is that certain code cannot be executed continuously and repeatedly without interruption. The first time the function is called, a timer is created to run code after a specified interval. When the function is called a second time, it clears the previous timer and sets one. The purpose is to execute the function again after the request to execute the function stops for a period of time.
The code is as follows:
//再来谈谈函数节流 function throttle(method,context){ clearTimeout(method.tId); method.tId = setTimeout(function(){ method.call(context); },100); } //该函数接受两个参数,第一个是要执行的函数,第二个是作用域。 //使用方法demo //未使用情况: window.onresize = function(){ var div = document.getElementByTagName(body); div.style.height = div.offsetWidth +'px'; } //使用情况; function resizeDiv(){ var div = document.getElementByTagName(body); div.style.height = div.offsetWidth +'px'; } window.onresize = function(){ throttle(resizeDiv); }; //只要代码是周期性执行的,都应该使用节流。
This does not give the user a great feeling, but it does reduce a lot of pressure on the browser. Function throttling is also one of the commonly used techniques in many frameworks.
The above is the relevant introduction to JavaScript advanced timer. I hope it will be helpful to everyone's learning.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function