如何在鼠标悬停时循环等待而不将所有事件放入调用堆栈 JS / Vue.js

How to wait in a loop on mouseover and not put all events in call stack JS / Vue.js

我在每次鼠标悬停时执行一次 api 调用,但我需要等待一秒钟并根据上次鼠标悬停执行一次 api 调用。

例如。如果用户将鼠标悬停在 10 个标题上,api 调用只会在他的鼠标停留一秒钟后完成。

这里有一个fiddle来说明(cf. network in inspector):https://codesandbox.io/s/search-a-la-mano-hpk92

因此,"mouseleave" 仅在用户离开元素时触发。

myElement.addEventListener("mouseleave", function( event ) {

并且事件对象传递一些关于其行为的信息。使用 event.relatedTarget 可以得到鼠标之前所在的元素。

不知道这是否有帮助,但您可以尝试一下

您可以使用 lodash.debounce for that. It just will call after the time you have passed. It only will execute the function within the last call parameters, avoiding unnecessary calls. You can check an example here.

你只需要用 debouce 函数包装你的函数

debounce(
  function (param1) { console.log('hello' + param1)},
  500
)