1. Background

Image stabilization

The function is shaking, and the shaking here means executing, whereas the general shaking is continuous, multiple times. Let’s say the function continues to execute multiple times, and we want it to calm down before we execute it. That is, when the event is fired continuously, the function is not executed at all until some time after the last firing.

The throttle

Throttling means to allow functions to be executed sparingly, rather than unsparingly when triggered. What does moderation mean? That is, only once over a period of time.

2. Classic examples

  1. Anti – shaking function: search page, user continuous input, wait to stop to trigger the search interface
  2. Throttling function: prevent button from connecting points


3. The Android implementation

  1. Code implementation:
object FunctionUtil {
    private const val DEFAULT_DURATION_TIME = 300L
    var timer: Timer? = null


    /** * anti-shaking function */
    fun debounce(duration: Long = DEFAULT_DURATION_TIME, doThing: () -> Unit){ timer? .cancel() timer = Timer().apply { schedule(timerTask { doThing.invoke() timer =null
            }, duration)
        }
    }

    /** * Throttle function */
    var lastTimeMill = 0L
    fun throttle(duration: Long = DEFAULT_DURATION_TIME, continueCall: (() -> Unit)? = null, doThing: () -> Unit) {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastTimeMill > duration) {
            doThing.invoke()
            lastTimeMill = System.currentTimeMillis()
        } else{ continueCall? .invoke() } } }Copy the code
  1. Use:
btn_sure.setOnClickListener {
    FunctionUtil.throttle {
        Log.i("nell-click"."hahah")
    }
}

btn_sure.setOnClickListener {
    FunctionUtil.throttle(500L) {
        Log.i("nell-click"."hahah")
    }
}

FunctionUtil.debounce {
	searchApi(text)
}
Copy the code

4. An RN implementation

  1. Code implementation:
/** * anti-shaking function */
function debounce(func, delay) {
  let timeout
  return function() {
    clearTimeout(timeout)
    timeout = setTimeout(() = > {
      func.apply(this.arguments)
    }, delay)
  }
}

/** * Throttle function */
function throttle(func, delay) {
    let run = true
    return function () {
      if(! run) {return
      }
      run = false // If run is always false, it will stop at the upper judgment
      setTimeout(() = > {
        func.apply(this.arguments)
        run = true // When the timer runs out of time, the switch is turned on and our function is executed
      }, delay)
    }
}

Copy the code
  1. Use:
throttle(function (e) {
  console.log("nell-click")},1000)


debounce(function (e) {
    searchApi(text)
}, 300)
Copy the code

5. The Flutter

  1. Code implementation:
class CommonUtil {
  static const deFaultDurationTime = 300;
  static Timer timer;

  // Anti-shaking function
  static debounce(FunctiondoSomething, {durationTime = deFaultDurationTime}) { timer? .cancel(); timer =new Timer(Duration(milliseconds: durationTime), () { doSomething? .call(); timer =null;
    });
  }

  // Throttling function
  static const String deFaultThrottleId = 'DeFaultThrottleId';
  static Map<String.int> startTimeMap = {deFaultThrottleId: 0};
  static throttle(Function doSomething, {String throttleId = deFaultThrottleId, durationTime = deFaultDurationTime, Function continueClick}) {
    int currentTime = DateTime.now().millisecondsSinceEpoch;
    if (currentTime - (startTimeMap[throttleId] ?? 0) > durationTime) { doSomething? .call(); startTimeMap[throttleId] =DateTime.now().millisecondsSinceEpoch;
    } else{ continueClick? .call(); }}}Copy the code
  1. Use:
GestureDetector(
      onTap: () => CommonUtil.throttle(onTap, durationTime: durationTime)
)


CommonUtil.debounce(searchApi)
Copy the code

End, scatter flowers 🎉