Throttling and anti-shock function are often asked in an interview, and can easily be confused. Here is the implementation of throttling and anti-shock function

1. The throttle

The core is the switch lock 🔒. For example, click the button multiple times to submit the form

Function throttle(fn, delay) {var timer = null, firstTime = true; return function () { if (timer) { return false; } var that = this; var args = arguments; fn.apply(that, args); timer = setTimeout(function () { clearTimeout(timer); timer = null; }, delay || 500); }; } // Use function clickHandler() {console.log(' throttling click! '); } const handler = throttle(clickHandler); document.getElementById('button').addEventListener('click', handler);Copy the code

2. If you

Perform only the last asynchronous task that was triggered to clear the previous asynchronous task, the core of which is to clear the zero. For example, the page scroll processing event is valid for the last time

Function debounce(fn, delay) {var timer = null; return function () { var that = this; var args = arguments; clearTimeout(timer); Timer = setTimeout(function () {fn.apply(that, args); }, delay || 500); }; } // Use function clickHandler() {console.log(' Click! '); } const handler = debounce(clickHandler); document.getElementById('button').addEventListener('click', handler);Copy the code

When it comes to confusing questions, just remember: throttling works the first time, anti-shaking works the other way around

3. The last

Recently, I have sorted out some interview questions of ali, Tencent, Byte and other big companies in order to understand the hot technical issues of big companies’ recruitment and improve my learning.

Which contains HTML, CSS, JavaScript, server and network, Vue, browser and so on, free to share to everyone, but also in the collection of collation, there is a need for friends【 Click on me 】Get it free.

Space is limited and only part of the content is shown