Contents
- Preface
- 1. Core and basic implementation
- 2. Throttling Advanced
- Write at the end
(Free learning recommendation: javascript video tutorial )
Preface
Let’s talk about throttling - the idea of another optimization function.
Let’s take the mobile event as an example
nbsp;html> <meta> <meta> <meta> <title>Document</title> <style> #wrapper { width: 100%; height: 140px; background: rgba(0, 0, 0, 0.8); color: #fff; font-size: 30px; font-weight: bold; line-height: 140px; text-align: center; } </style> <p></p> <script> var count = 1; function moveAction () { oWrapper.innerHTML = count++; } var oWrapper = document.querySelector('#wrapper'); oWrapper.onmousemove = moveAction; </script>
The effect is as follows:
1. Core and basic implementation
The principle of throttling is very simple: If you continuously trigger an event, it will only be executed once within a specific time interval.
Regarding the implementation of throttling, there are two mainstream implementation methods:
- Time stamp idea
- Timer idea
1.1 Timestamp idea
As the name suggests, the time interval is controlled through two timestamps. When an event is triggered:
- We take out the current Timestamp
now
; - Then subtract the timestamp of the previous execution (the first value is 0)
prev
; - If big
now - prev > wait
, it proves that the time interval maintenance is over, executes the specified event, and updatesprev
;
According to this idea, we You can now implement the first version of the code:
oWrapper.onmousemove = throttle(moveAction, 1000);function throttle(func, wait) { var _this, arg; var prev = 0; // 上一次触发的时间,第一次默认为0 return function () { var now = Date.now(); // 触发时的时间 _this = this; if (now - prev > wait) { func.apply(_this, arg); // 允许传入参数,并修正this prev = now; // 更新上一次触发的时间 } }}
Let’s see what the effect is like with the help of it:
We can see:
- When the mouse moves in, the event is executed immediately
- It will be executed once every 1s, and it will be executed twice after moving for 2.5s, which means the action will not be executed again after stopping.
1.2 Timer idea
Use timer to ensure the number of triggers of events within the interval
- Create timer
timer
, record whether it is currently within the period; - Determine whether the timer exists, if it exists, it will end directly, otherwise the event will be executed;
-
wait
time Then execute it again and clear the timer;
When the event is triggered, we set a timer. When the event is triggered again, if the timer exists, it will not be executed until the timer is executed. , and then execute the function to clear the timer, so that the next timer can be set.
function throttle(func, wait) { var _this, arg; var timer; // 初始化 return function () { _this = this; // 记录this arg = arguments; // 记录参数数组 if (timer) return; // 时候未到 timer = setTimeout(() => { func.apply(_this, arg); // 允许传入参数,并修正this timer = null; }, wait); }}
Let’s see what the effect is like with the help of it:
However, we can see:
- When the mouse is moved in, the event will not be executed immediately;
- After the mouse is customized
wait
It will be executed once after an interval
1.3 The difference between the two ideas
Timer | ||
---|---|---|
Execute immediately | Execute after n seconds | |
Will not be executed after stopping | Stop will be executed again |
2. Throttling advancement
Combining two ideas to complete one can be executed immediately , and the throttling method to execute again after stopping the trigger:// 第三版function throttle(func, wait) { var timeout, context, args, result; var previous = 0; var later = function() { previous = +new Date(); timeout = null; func.apply(context, args) }; var throttled = function() { var now = +new Date(); //下次触发 func 剩余的时间 var remaining = wait - (now - previous); context = this; args = arguments; // 如果没有剩余的时间了或者你改了系统时间 if (remaining wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } }; return throttled;}The effect is demonstrated as follows:
Related free learning recommendations: javascript (Video)
The above is the detailed content of JavaScript Topic 4: Throttling. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona


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

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

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool