In JavaScript, Throttle, Debounce, and Immediate are regularly controlled. throttledebounce

Source: Internet
Author: User

In JavaScript, Throttle, Debounce, and Immediate are regularly controlled. throttledebounce

Preface

We call these actions events and respond to callbacks ). A continuous event stream is called an event stream ). The speed at which these behaviors occur is not manually controlled. However, we can control when and how to activate the correct response. Some technologies provide us with precise control.

Throttle

In modern browsers, the frame rate of 60fps is the goal of smooth performance. Given our Ms time budget, it is used to respond to all the updates required by some events. In this way, it can be inferred that if n events occur per second and the callback is executed, it takes t s to run smoothly,

1 / n >= t

If t is in milliseconds,

1000 / n >= t

If you have used the mousemove event, you will know that the number of mousemove events generated can exceed 60 times per second. If our callback needs to exceed 16.7 ms, it will start to be messy.

var then = 0; function log() { var now = Date.now(); if (1000 / (now - then) > 60) {  console.log('It\'s over 9000!!!'); } then = now;} window.onmousemove = log;

Implementation

Throttle allows us to limit the number of responses we activate. We can limit the number of callbacks per second. That is, the amount of time to wait before the next Callback is activated;

var delta = 1000;var then = 0; function log() { console.log('foo');} function throttledLog() { var now = Date.now(); if (now - then >= delta) {  log();   then = now; }}; window.onmousemove = throttledLog;

We can replace delta with fps and infer different codes.

var fps = 60;...function throttledLog() { var now = Date.now(); if (1000 / (now - then) < = fps) {  log();   then = now; }}; window.onmousemove = throttledLog;

We can also use setTimeout to achieve the same result. However, it is not the check time difference, but the check status change.

For the first time, we can safely activate the callback. Once completed, the callback can be activated again only after waiting for the delta time.

var delta = 1000;var safe = true; function log() { console.log('foo');} function throttledLog() { if (safe) {  log();   safe = false;  setTimeout(function() {   safe = true;  }, delta); }}; window.onmousemove = throttledLog;

Debounce

This term-dejitters come from the field of electronics, where a manually switched input signal is sent to a digital circuit. In electronics, when you press a physical button once, the digital circuit may read multiple presses because of the physical properties of the button (metal contacts, springs, worn parts, etc ).

Dejittering means all these fluctuating signals are collected and treated as one.

Example

A simple example already exists in JS: keydown vs keyup. Assume that you are processing a project and you need to enter the content. However, you want to obtain a character each time you press the keyboard. During input, if you press a key for a long time, the keydown event is triggered continuously, but the keyup event is triggered only when the key is released.

window.onkeyup = function() { console.log('onkeyup');} window.onkeydown = function() { console.log('onkeydown');}

This behavioral difference is useful for determining whether the input is complete. In the example scenario, it is the keyup event you will use. To some extent, we can say that keydown is the original input, and keyup is the dejitters input.

Implementation

When an event occurs, callback is not activated immediately. On the contrary, we wait for a certain period of time and check whether the same event is triggered again. If yes, we reset the timer and wait again. If no same event occurs during the waiting period, we activate the callback immediately.

var delta = 1000;var timeoutID = null; function log() { console.log('foo');} function debouncedLog() { clearTimeout(timeoutID); // reset timer timeoutID = setTimeout(function() {  // wait for some time  // and check if event happens again  log(); }, delta);}; window.onkeydown = debouncedLog;

Immediate

Immediate is the exact version of Debounce. Compared with Debounce waiting for subsequent event triggering and then activating the callback, Immediate activates the callback immediately and waits for subsequent events to be triggered within a certain period of time.

Implementation

Just like Throttle, we need a state variable to check whether our callback should be activated. We don't need one in Debounce, because timeoutID implicitly manages this part.

var delta = 1000;var timeoutID = null;var safe = true; function log() { console.log('foo');} function immediatedLog() { if (safe) {  log();  safe = false; }  clearTimeout(timeoutID); timeoutID = setTimeout(function() {  safe = true; }, delta);}; window.onkeydown = immediatedLog;

Summary

The above is all about this article. In this article, we have explored the most common technologies used as scheduled functions. I hope the content of this article will help you in your study or work. If you have any questions, you can leave a message.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.