Skip to content

Throttling

  • Throttle: Run at fixed intervals while an event keeps triggering. “I will respond at a fixed interval while you talk.”

HTML

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" onkeyup="throttleSendData1000(`Chandan`)">
</body>
<script src="./throttle.js"></script>
</html>

JavaScript

js
let counter = 0
function sendData(name){
    console.log("Data being sent: ",name,",",counter++)
}

function throttle(fn,t){
    let flag = true;
    return function(...args){
        if(flag){
            fn.apply(this,args);
            flag = false;
            setTimeout(()=>{
                flag=true;
            },t)
        }
    }
}

const throttleSendData1000 = throttle(sendData,1000)