Search code examples
loopsvue.jswaitonmouseover

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


I do an api call at each mouseover but I need to wait one second and perform a single api call according to the last mouseover.

Ex. If the user mouseover on 10 titles, the api call will be done only after his mouse stay one second on.

Here's a fiddle to illustrate (cf. network in inspector) : https://codesandbox.io/s/search-a-la-mano-hpk92


Solution

  • You can use 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.

    You only have to wrap your function with the debouce function

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