JS advanced-anti-shake and throttling

JS advanced-anti-shake and throttling

1. Anti-shake

In frequent operations, the anti-shake function is executed once after the specified time after the operation is completed. For
example, you need to send a request to obtain the search results after the input is completed in the input box. Add a layer of anti-shake to the input event function to achieve this function

var debounce = function(fn = function() {}, delay = 0) {
    var args = [].slice.call(arguments, 2)
    var timer,
        _args,
        _this

    return function() {
        _this = this
        _args = [].slice.call(arguments)
        timer && clearTimeout(timer)
        timer = setTimeout(function() {
            fn.apply(_this, args.concat(_args))
        }, delay)
    }
}
 

2. Throttling

During frequent operations, the throttled function will be executed every specified time during the operation. For
example: click the button to draw, set the throttle time to 1s, and frequently click the button for 4s, then the throttled function will be executed every 1s Execute once, that is, execute 4 times in total

var throttle = function(fn = function() {}, delay = 0) {
    var args = [].slice.call(arguments, 2)
    var last = 0
    var now = 0
    var _args,
        _this

    return function() {
        now = Date.now()
        if (now - last < delay) {
            return
        }
        last = now
        _this = this
        _args = [].slice.call(arguments)
        fn.apply(_this, args.concat(_args))
    }
}
 

3. Examples

  • html
<input type="text" id="ipt"/>
<button id="btn"> </button>
 
  • js
function iptHandler(a, e) {
  console.log('ipt', a, e)
}

function btnHandler(a, e) {
  console.log('btn', a, e)
}

var debouncedIpt = debounce(iptHandler, 1000, 1)
var throttleBtn = throttle(btnHandler, 1000, 1)

ipt.oninput = debouncedIpt
btn.onclick = throttleBtn
 
  • effect
    • Anti-shake effect
    • Throttle effect