Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使mousemove处理程序中的回调异步_Javascript_Reactjs - Fatal编程技术网

Javascript 使mousemove处理程序中的回调异步

Javascript 使mousemove处理程序中的回调异步,javascript,reactjs,Javascript,Reactjs,我有以下事件处理程序。由于它们发生的频率,这将是相当“贪婪”的onMouseMove,它将在选定区域周围绘制一个“套索”,然后在该区域周围执行限制的地理空间搜索 onMouseMove = ({ pageX, pageY }: MouseEvent) => { const lasso = this.getLasso(pageX, pageY); this.ctx.setLineDash([6]); this.ctx.strokeStyle = '#ffffff'; this

我有以下事件处理程序。由于它们发生的频率,这将是相当“贪婪”的
onMouseMove
,它将在选定区域周围绘制一个“套索”,然后在该区域周围执行限制的地理空间搜索

onMouseMove = ({ pageX, pageY }: MouseEvent) => {
  const lasso = this.getLasso(pageX, pageY);
  this.ctx.setLineDash([6]);
  this.ctx.strokeStyle = '#ffffff';
  this.ctx.strokeRect(lasso.left, lasso.top, lasso.width, lasso.height);

  // this is the problem area.
  this.props.onSelection(this.search(lasso));
}
然而,我发现callstack主要是运行这个回调。更新“套索”的操作仅需2毫秒,但
onSelection
回调需要约40毫秒。在性能方面,它们都分组在
事件(mousemove)
下。我认为这使得套索的动画看起来非常起伏

有没有办法从鼠标事件处理程序独立/异步运行此回调?当mousemove事件完成时,它与它没有多大关系。

使用时延迟为0。它将被添加到JavaScript调度程序队列,并在当前调用堆栈完成后运行

在现场,这变成:

onMouseMove = ({ pageX, pageY }: MouseEvent) => {
  const lasso = this.getLasso(pageX, pageY);
  this.ctx.setLineDash([6]);
  this.ctx.strokeStyle = '#ffffff';
  this.ctx.strokeRect(lasso.left, lasso.top, lasso.width, lasso.height);

  // this is the problem area.
  setTimeout(function () { this.props.onSelection(this.search(lasso));});
}
默认为0,可以省略,如链接单据所示:

如果省略此参数,则使用值0,表示“立即”执行,或更准确地说,尽快执行。注意,在任何一种情况下,实际延迟可能比预期的时间长;见下文


如果确实需要,也可以使用
requestAnimationFrame
want@Ven我假设OP会在问题区域之前调用它,那么重新渲染是在慢速回调完成之前发生的?“我以前从来没有用过它。”安德烈亚斯:是的,我的本意是不浪费工作。我现在明白了,你的第一句话是想引起我的思考。我开始明白你的意思了。没有链接就一文不值。
window.requestAnimationFrame
做得很好!非常感谢。sir@corvid你能把这个作为回答吗?我很想看看它是怎么工作的。我从未使用过
requestAnimationFrame
您应该使用Web Worker-它将启动一个单独的线程,以避免阻塞主线程。