Home  >  Article  >  Web Front-end  >  Introduction to the usage of JS function throttling (code example)

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

不言
不言forward
2019-02-20 13:51:242915browse

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);
}

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);
}
function fn(cb,context){
clearTimeout(cb.Tid);
cb.Tid=setTimeout(function(){
    cb.call(context);
},500);
}
window.onresize=function(){
fn(resizehandler,window);
};

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete