0

I need to create a 'select by hover' (dwell) effect in my application and it is crucial to be timely and accurate. This needs to trigger just once for every timeout call and must not loop. The dwell function is attached to an element (getElementById).

My implementation at the moment sometimes works brilliantly and sometimes takes a lot of time to complete. Sometimes the callback just doesn't trigger after the setTimeout.

dwell: (elem, select) => {
   var timeout = 0
    elem.onmouseover = () => {
      timeout = setTimeout(select, dwellTime)
    }

    elem.onmouseout = () => {
      clearTimeout(timeout)
    }
  }

The select callback function must execute EXACTLY after the dwellTime has elapsed. Any ideas please?

danielmt
  • 1
  • 3
  • 3
    Can you create a [mcve]? –  Apr 09 '19 at 21:11
  • 2
    See https://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout – PM 77-1 Apr 09 '19 at 21:14
  • 1
    Browsers are not real-time platforms. – Pointy Apr 09 '19 at 21:16
  • Possible duplicate of [Is there a more accurate way to create a Javascript timer than setTimeout?](https://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout) – Nicholas Tower Apr 09 '19 at 21:19
  • 2
    JavaScript is single-threaded and non-preemptive. If it's busy doing something else when the timeout is reached, it won't interrupt it to execute the timer function. – Barmar Apr 09 '19 at 21:29
  • Any ideas on alternatives I can use for this? – danielmt Apr 10 '19 at 09:58
  • @Danielmt Welcome to SO! At this point it seems to me that it becomes more of an X/Y problem: you want a hover-to-select feature, you use setTimeout to implement it, there are some issues and you blame setTimeout (with some reason, but that is a limitation of JS). To find a suitable workaround, we would need more details about your issue (ideally an MCVE) and explanations about what compromise you can make. – ghybs Apr 12 '19 at 02:37

0 Answers0