'Is there a way to manually add delay to all user input DOM events?

For a research experiment I am trying to delay the user interface (create lag) on mobile browsers, as I am researching the effects of UI latency in webapps. For example, if a user scrolls the scroll action only happens (e.g.) 50ms later.

I've tried window.addEventListener(), and then window.dispatchEvent() after a certain delay with setTimeout(). Howver, in the case of scrolling, this did not scroll the page after dispatching the event manually. Scrolling with window.scrollBy() does work, but it fires its own event.

window.addEventListener('wheel', event => {
    console.log(event)
    if (event.cancelable) {
        event.preventDefault()
        event.stopImmediatePropagation()
        setTimeout(() => {
            let newEvent = new WheelEvent('wheel', {
                deltaX: event.deltaX,
                deltaY: event.deltaY,
                deltaZ: event.deltaZ,
                cancelable: false,
            })
            window.dispatchEvent(newEvent)
            // window.scrollBy({ top: 20 })
        }, DELAY)
    }
}, {
    capture: true,
    passive: false,
})

This works for wheel events, but not for touch events. If there a way to generalize this behaviour for all MouseEvents? Ideally I would like to process all DOM MouseEvent's, like some sort of middleware.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source