Home > Web Front-end > JS Tutorial > body text

Introduction to the usage of JS function throttling (code example)

不言
Release: 2019-02-20 13:51:24
forward
2994 people have browsed it

This article brings you an introduction to the usage of JS function throttling (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Nowadays, the uses of JavaScript are really wide. It feels like you can do anything, such as doing video surveillance to see what the person you like is doing at all times. Oh my god, this is illegal, no, no, no.

Recently I encountered a need at work: a requirement that was originally for PC-side framework configuration. Now the leader suddenly asked me to make it compatible with mobile sizes from the PC side. My head hurt instantly, because all the used It’s in px units, it’s not good, it really hurts, and then I thought that I need to change the size of some page elements when the browser window changes
Original size

Introduction to the usage of JS function throttling (code example)

Configure it for mobile At that time

Introduction to the usage of JS function throttling (code example)

function resizehandler(){
console.log(new Date().getTime());
console.log(++n);
}
Copy after login

Then I tried dragging the window and looked at the console and it actually printed 50 times. This is not what I want. As a Reasonable code only needs to be executed once. The code in the function may be complicated, but it is what I want.
I searched online and there is a function throttling specifically to deal with this problem in advanced JavaScript programming.

The principle is very simple. Use a timer to delay function execution for 500 milliseconds. If there is a function within 500 milliseconds, it will When called, the previous call will be deleted, and this call will be executed 500 milliseconds later, and so on

let n=0;
function resizehandler(){
console.log(new Date().getTime());
console.log(++n);
}
Copy after login
function fn(cb,context){
clearTimeout(cb.Tid);
cb.Tid=setTimeout(function(){
    cb.call(context);
},500);
}
Copy after login
window.onresize=function(){
fn(resizehandler,window);
};
Copy after login

This will achieve the desired effect

Introduction to the usage of JS function throttling (code example)

The above is the detailed content of Introduction to the usage of JS function throttling (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template