Blog>
Snippets

Debounce with Dynamic Delay

Create an example where the debounce delay duration is dynamically adjusted based on user interaction or other runtime conditions.
var lastInteractionTimestamp = 0;
var debounceDelay = 200; // Initial debounce delay in milliseconds

function dynamicDebounce(func) {
  var timer;
  return function() {
    var context = this;
    var args = arguments;
    var now = Date.now();
    var timeSinceLastInteraction = now - lastInteractionTimestamp;
    
    // Adjusting debounce delay based on time since last interaction
    if(timeSinceLastInteraction < 500) { // If last interaction was less than 500ms ago
      debounceDelay = 300; // Increase delay
    } else if(timeSinceLastInteraction < 1000) { // If last interaction was less than 1s but more than 500ms ago
      debounceDelay = 200; // Medium delay
    } else {
      debounceDelay = 100; // Decrease delay
    }
    
    clearTimeout(timer);
    timer = setTimeout(function() {
      func.apply(context, args);
    }, debounceDelay);
    
    lastInteractionTimestamp = now; // Update last interaction timestamp
  };
}
This code snippet provides a dynamic debounce function, which dynamically adjusts the debounce delay according to the time passed since the last user interaction. It starts with a defined initial delay but increases the delay if interactions occur in rapid succession, and decreases it if interactions are more spaced out. This allows for a more responsive interface during periods of high interaction while ensuring performance is not compromised by too many function calls during periods of continuous interaction.