Add EventListener Sub Flags

Add EventListener Sub Flags

EventListeners allow the addition of a preset delay before firing the callback parameter (event throttling).
However to reduce bandwith when polling a remote server, and because the number of keystrokes-, scrolling-, mousemove- or resize events is non deterministic,
it is more useful to "batch" events and fire the callback once

This may be so common in use today it may be beneficial to add it to the standard

REFERENCE

// CURRENT //

const input = document.getElementById("input")
const defaultText = document.getElementById("defaultText")
const debouncedText = document.getElementById("debouncedText")
const throttleText = document.getElementById("throttleText")
const mouseEvents = document.getElementById("mouseEvents")

function debounce(cb, delay = 1000){
    let timeout = null
    return (...args) => {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
            cb(...args)
        }, delay)
    }
}

const updateDebouncedText = debounce(text => {
    defaultText.textContent = text
}, 250)

function throttle(cb, delay = 1000){
    let shouldWait = false
    let waitingArgs = null
    const timeoutFunc = () => {
        if(shouldWait == null){
            shouldWait = false
        } else {
            cb(...waitingArgs)
            waitingArgs = null
            setTimeout(timeoutFunc, delay)
        }
    }
    return (...args) => {
        if (shouldWait){
            waitingArgs = args
            return
        }
        cb(...args)
        shouldWait = true
        setTimeout(timeoutFunc, delay)
    }
}

const updateThrottleText = throttle(text => {
    defaultText.textContent = text
}, 250)

input.addEventListener("input", e => {
    defaultText.textContent = e.target.value
    updateDebouncedText(e.target.value)
    updateThrottleText(e.target.value)
}, false)

// NEW //

input.addEventListener("post.batch.input", e => {
    debouncedText.textContent = e.target.value
}, 250) // fire callback on input event[s], batched as a single event, during delay (ie "a","b" == "ab") //

input.addEventListener("pre.throttle.input", e => {
    debouncedText.textContent = e.target.value
}, 250) // fire callback only on last event received during delay (ie "a","b" == "b") //

input.addEventListener("pre.throttle.mousemove", e => {
    mouseEvents.textContent = e.target.value
}, 250) // fire callback only on last event received during delay (ie "[100,30]","[-50,30]" == "[-50,30]") //
1 Like

Event listeners aren't part of the language standard; you'll want to head to https://github.com/whatwg/html for that.

Done!

You can follow the discussion, and add your own comments here:

Add EventListener Sub Flags [Suggestion] [Feature Request] · Issue #7780 · [whatwg/html · GitHub] - https://github.com/whatwg/html/issues/7780