-5

I want when i hover on element to count 4 seconds for example and then do the action. But only if user really hover on that element 4 seconds, i dont want to use setTimeout function.

I found this example:

How to check how long you hover an element in pure javascript?

but this only count when user do mouseout. I want to do calculation on mouseover and if pass 4 seconds do something. Any suggestion?

None
  • 8,817
  • 26
  • 96
  • 171
  • I would say this is exactly the job for `setTimeout`. Only other thing with plain javascript would be `setInterval` with an interval of 1000ms an count to 4. Why can't you use `setTimeout`? – Michael Jul 16 '22 at 12:33
  • if i hover on element and use settimeout it will only delay some action which i want to do for 4 second...i want to check if user really hover on element 4 second and then call action...if im a littlebit clear what i want to achive ? – None Jul 16 '22 at 12:37
  • 1
    yes, got it. the function would still trigger if the user moves the mouse out of the object within the four second delay – Michael Jul 16 '22 at 12:39
  • yes..thats why settimeout is not good option for me :) – None Jul 16 '22 at 12:40
  • what about using mouseenter and mouseout instead? mouseenter to start the timer wtih 4 second delay, store the timer handle in a global variable. if the user leaves the object mouseout should be triggered and you can clear the timer handle before it triggers – Michael Jul 16 '22 at 12:42
  • i want something like tooltip where i will call external services..so when user hold mouse on that element i will call external service and display data in that tooltip...if i move mouse there is no point then to call service then – None Jul 16 '22 at 12:45

2 Answers2

1

As an alternative to the previous answer with setInterval

var handle = null

function enter() {
  handle = setTimeout(function() {
    alert('mouse in for 4s');
  }, 4000);
}
function out() {
  clearTimeout(handle);
}
<button onmouseenter="enter()" onmouseout="out()">test</button>
Michael
  • 1,931
  • 2
  • 8
  • 22
  • [Why is using onClick() in HTML a bad practice?](https://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice) – jabaa Jul 16 '22 at 12:54
0

Here is an example if the code not clear tell me in comment section, i will provide some more explanation if needed

const button = document.getElementById("hover")
let date = null
let timer
button.addEventListener("mouseover", function () {
    if(!date) date = new Date()
    timer = setInterval(()=>{
        if((new Date() - date) >= 4000) {
        console.log('Do Action')
        clearInterval(timer)
        }
    }, 1000)
}, false)

button.addEventListener("mouseout", function () {
    clearInterval(timer)
    date = null
})
<body>
    <button id='hover'>Hover Me</button>
</body>
ZomitaKa
  • 475
  • 2
  • 7