JavaScript-timed control throttle, debounce and immediate detailed _javascript tips

Source: Internet
Author: User

Objective

We call these acts events, and response callbacks (callbacks). A continuous flow of events is called the event stream (a stream of events). The speed at which these actions occur is not something we can control manually. But we can control when and how to activate the correct response. There are some technologies that provide us with precise control.

Throttle

In modern browsers, the frame rate of 60fps is the goal of fluent performance, given our 16.7ms time budget to respond to all the required updates for some events. This makes it possible to infer that if n events occur every second and the callback is executed, it takes a time of t seconds, in order to run smoothly,

1 / n >= t

If T is measured in milliseconds,

1000 / n >= t

If you have ever used the MouseMove event, you will know that the number of MouseMove events can exceed 60 times per second. If our callback needs to be more than 16.7ms, it will start to clutter up.

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

Realize

Throttle allows us to limit the number of responses we activate. We can limit the number of callbacks per second. In turn, that is to say, how long to wait before activating the next callback;

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 the delta with FPS and infer different code.

var fps =;
...
function Throttledlog () {
 var now = Date.now ();
 if (1000/(Now-then) < = fps) {
  log ();
 
  then = Now;
 }
;
 
Window.onmousemove = Throttledlog;

We can also achieve the same results by using settimeout. However, instead of checking the time difference, check the status changes.

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

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-to shake the field from the electronics, the manual switch input signal is sent to the digital circuit. In electronics, when you press a physical button once, a digital circuit may read multiple presses because of the physical properties of the button (metal contacts, springs, wear parts, etc.).

Dithering means capturing all the signals of these fluctuations and treating them as one.

Example

A simple example already exists in JS: KeyDown vs KeyUp. Let's say you're working on a project and you need to enter something. But you want to get a character every time you tap the keyboard. When entered, if a key is pressed long, the KeyDown event is triggered sequentially, 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 has been completed. In the example scenario, it is the KeyUp event that you will use. In a way, we can say that KeyDown is the original input, KeyUp is to jitter input.

Realize

When the event occurs, we do not activate the callback immediately. Instead, we wait a certain amount of time and check whether the same event is triggered again. If yes, we reset the timer and wait again. If the same event does not occur during the wait 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. Rather than debounce wait for subsequent events to trigger and then activate the callback, Immediate activates the callback immediately and waits for subsequent events to be triggered within a certain amount of time.

Realize

As in the case of 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;

Summarize

This is the whole story of this article, and in this article we have explored the most common techniques used as timing functions. I hope the content of this article for everyone's study or work can bring certain help, if there is doubt you can message exchange.

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.