【问题标题】:How to track when mousemove ends [duplicate]如何跟踪mousemove何时结束[重复]
【发布时间】:2021-03-01 22:27:18
【问题描述】:

我想在mousemove 结束时调用一个函数。

我有一个像下面这样的onmousemove 事件监听器,它触发了太多次:

window.onmousemove = (e) => { console.log(e) }

我想减少调用该函数的频率以防止高负载。

例如,当光标停止时调用该函数一次。

如果还有其他解决方案,我也很乐意尝试。

【问题讨论】:

标签: javascript


【解决方案1】:

您可以将事件回调包装在debounce function 中。只有在开始移动鼠标后停止 1/4 秒时,才会调用此包装函数。如果您在停止后 250 毫秒内开始移动,超时将重置并等待您再次停止。

const debounce = function(func, wait, immediate) {
  let timeout;
  return function() {
    const
      context = this,
      args = arguments,
      later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      },
      callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

const onMouseMove = (e) => {
  console.log(`Stopped position: (${e.clientX}, ${e.clientY})`);
};

const debounceMouseMove = debounce(onMouseMove, 250); // 1/4 of a second

document.addEventListener('mousemove', debounceMouseMove);

【讨论】:

    【解决方案2】:

    没有办法直接做到这一点。但你可以试试这个:

    var timeout;
    element.onmousemove = function (e) {
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(function() {
            // do your stuff here
        }, 200);
    }
    

    如果 200 毫秒内没有检测到事件,它将触发。

    【讨论】:

    • 谢谢。它看起来棒极了。会试一试的!
    • 你忘记分配timeout
    • 它仍然触发 相同 数量的事件,但只是超时,我说得对吗?
    • 不,它会清除每个事件的超时时间。
    • @SystemsRebooter 请立即尝试,我修复了一个错误。
    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2013-07-03
    相关资源
    最近更新 更多