【问题标题】:JavaScript Named functions and Event handlers regarding CPU consumption关于 CPU 消耗的 JavaScript 命名函数和事件处理程序
【发布时间】:2022-02-10 03:20:53
【问题描述】:

按照@FlorianMargaine 的建议(在 JavaScript 聊天对话中)重构我的代码后,我得到了如下所示的内容:

body.addEventListener( 'mousedown', action1);
function action1(){
    //Start selecting event
    body.addEventListener( 'mousemove', selectOver);
}
function selectOver(e){
    //after the user has selected and done a mouse up event show a box:
    body.addEventListener( 'mouseup', showBox );
}
function showBox(e){
    //Show box
    box.addEventListener( 'click', actionAlert('clicked on interface after selected text') );
}
function actionAlert(d){
    alert(d);
}

主要问题是我认为它在途中使用了很多 CPU,我怎样才能最大限度地减少它? 我读了一些关于删除事件处理程序的能力,这是解决方案吗?以及如何将该解决方案有效地集成到代码中?

【问题讨论】:

  • 你确定这就是你所追求的吗?您将actionAlert 的返回值传递给addEventListener,这是undefined 而不是函数。
  • 这是一个定义不明确的问题。你的目标是什么?你的代码应该做什么?
  • “我认为它在途中会占用大量 CPU” -- 为什么您会这么认为?我并不是说这样想就一定是错误的,但是是什么工具让你这么想的?在问题中包含该信息。

标签: javascript dom-events cpu-usage


【解决方案1】:

edit在使用“addEventListener”时这是不正确的,但我将把它留在这里作为历史的好奇:)你的“action1”事件处理程序每​​次重新绑定“mousemove”处理程序叫。反过来,该处理程序为“mouseup”绑定一个新的处理程序。过一会儿,就会有成百上千的冗余处理程序。

所以,教训是:不要在其他事件处理程序中绑定事件处理程序(除非你真的有充分的理由)。 (edit — 抱歉;正如我在上面所写的,有人指出这都是不正确的。我习惯于使用 jQuery 绑定处理程序,并且该库的行为方式不同。)

另外:您的“showBox”函数,如所写,绑定调用“actionAlert”方法的结果,该方法没有返回值。我想你想要的是:

box.addEventListener( 'click', function() {
  actionAlert('clicked on interface after selected text');
});

【讨论】:

  • 其实.addEventListener不会多次添加同一个函数。来自w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/…If multiple identical EventListeners are registered on the same EventTarget with the same parameters the duplicate instances are discarded.
  • 执行 冗余 绑定应该不是问题,除非您使用匿名函数 -- 连续两次使用 addEventListener 的相同函数引用 will not bind the function twice。不过,OP 代码中缺少removeEventListener 可能是个问题。只是想指出附加冗余绑定和无法删除旧绑定之间的区别。
  • 啊,对不起,我只是习惯了 jQuery(它将添加它们):-)
【解决方案2】:

您不应在每个 mousemove 上添加 mouseup 的事件侦听器,也不应在每次 mousedown 时重新-注册 mousemove 而是:

body.addEventListener( 'mousedown', action1, false);
function action1(){
    //Start selecting event
    body.addEventListener( 'mousemove', selectOver, false);
    body.addEventListener( 'mouseup', showBox, false );
    body.addEventListener( 'mouseup', function(){
      body.removeEventListener( 'mousemove', selectOver, false );
    });
}
function selectOver(e){
    // Not sure what this function is for.
}
function actionAlert(d){
    alert(d);
}

我还添加了显式的第三个参数 falseaddEventListener,这是某些(全部?)Firefox 版本的要求。

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2023-01-27
    • 2014-03-16
    • 1970-01-01
    相关资源
    最近更新 更多