How to debounce events in Mithril.js

Published on in JavaScript and Mithril.js

Last updated on

Disable auto-redraw with event.redraw = false and use a timeout.

Disabling auto-redraw is mentioned on the Auto-redraw system page in Mithril docs:

Mithril automatically redraws after DOM event handlers that are defined in a Mithril view. You can disable an auto-redraw for specific events by setting e.redraw to false.

Example using an oninput event:

const App = () => {
  let timeout
  let value = '25'

  function oninput(e) {
    e.redraw = false

    // Update state because we are using a controlled component
    value = e.currentTarget.value

    clearTimeout(timeout)
    timeout = setTimeout(() => {
      // Do something more here if needed

      // Plus probably redraw manually
      m.redraw()
    }, 1000)
  }

  return {
    view: () => [
      m('input[type=text]', { oninput, value }),

      // Updating of this value is debounced
      m('p', Math.sqrt(value)),
    ],
  }
}

I'm not sure how much I like this solution because it feels like it's not proper debouncing. What if a global auto-redraw is triggered elsewhere? It might be a problem in some cases.

Can you think of a better way to debounce events in Mithril.js? Lemme know!