It’s an old question, so let’s look at a specific example.

Image stabilization

If the command is constantly triggered, the command is not executed. Until the specified time is reached, no further click, execute.

function debounce(fn, wait) {
            let time = null;
            return function (. args) {
                // Stop each click to identify tasks that are delayed
                time && clearTimeout(time);
                // Otherwise, start the delayed task
                time = setTimeout(() = > {
                    fn(...args)
                }, wait);
            }
        }
Copy the code

The sample application

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, "> <title>Document</title> </head> <body> <div id="content" style="height: 150px; line-height: 150px; text-align: center; color: #fff; background-color: #000; font-size: 100px;" > </div> <script> let num = 1; const content = document.getElementById('content'); function count() { content.innerText = num++ } function debounce(fn, wait) { let time = null; return function (... Args) {// Stop time && clearTimeout(time); Time = setTimeout(() => {fn(... args) }, wait); } } content.addEventListener('mousemove', debounce(count, 300)) </script> </body> </html>Copy the code

The number is increased by one until there is no click within 300ms.

The throttle

Triggers frequently and only executes once within a specified period of time.

// Timestamp version
function throttle(fn, wait) {
            let pre = Date.now();
            return function (. args) {
                let now = Date.now();
                if (now - pre > wait) {
                    pre = now;
                    console.log(pre); fn(... args) } } }// Timer version
function throttle(fn, wait) {
            let time = null;
            return function (. args) {
                if(! time) { time =setTimeout(() = > {
                        // fn.apply(this, args);fn(... args) time =null}, wait); }}}Copy the code

The sample application

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, "> <title>Document</title> </head> <body> <div id="content" style="height: 150px; line-height: 150px; text-align: center; color: #fff; background-color: #000; font-size: 100px;" > 1 </div> <script> let num = 1; const content = document.getElementById('content'); function count() { content.innerText = num++ } function throttle(fn, wait) { let time = null; return function (... args) { if (! time) { time = setTimeout(() => { fn(... args) time = null }, wait); } } } content.innerText = addEventListener('mousemove', throttle(count, 1000)) </script> </body> </html>Copy the code

The mouse is triggered once every second while moving.


Record the record!