0

I wanted to throttle down some mouse events to reduce CPU impact, but it seems that one method stops working while inside of throttle.

Before:

DrawPolygon.onMouseMove = function(state, e) {
  if (isVertex(e) || isMidpoint(e)) {
    this.updateUIClasses({
      mouse: Constants.cursors.POINTER
    })
  }

  if (this.CursorVertex(state)) {
    this.updateCursorVertex(state, e)
  }

  this.StopDragging(state, e)
}

After:

DrawPolygon.onMouseMove = function(state, e) {
  throttledWrite(() => {
    if (isVertex(e) || isMidpoint(e)) {
      this.updateUIClasses({
        mouse: Constants.cursors.POINTER
      })
    }

    if (this.CursorVertex(state)) {
      this.updateCursorVertex(state, e)
    }

    this.StopDragging(state, e)
  })
}

throttle:

function throttle(timer) {
  let queuedCallback
  return callback => {
    if (!queuedCallback) {
      timer(() => {
        const cb = queuedCallback
        queuedCallback = null
        cb()
      })
    }
    queuedCallback = callback
  }
}
const throttledWrite = throttle(requestAnimationFrame)

So... The problem is that this.updateUIClasses works properly without throttle, but is totally useless inside of it. I know that arrow functions pass local scope to this... But it seems that I'm losing something in the process and I'm not sure why.

This method is defined as an interface here: https://github.com/mapbox/mapbox-gl-draw/blob/main/src/modes/mode_interface_accessors.js#L159

This method is visible when I console.log(this) inside of throttle. But using it does literally nothing. Maybe it updates some other (newly created/copied context) that I don't know about?

So, my question is:

Why does the method this.updateUIClasses produce different result while called inside of throttle?

Crow
  • 4,635
  • 3
  • 14
  • 21

0 Answers0