views:

63

answers:

1

I have a function called goRight() which does some stuff when I click a div called "goright".

I want to make it so that when I hover over the div "goright" it will call the function repeatedly (with a small delay) for as long as I'm hovering, and then do nothing and stop once i move the mouse away.

I have experimented with setInterval but I think I'm misunderstanding how it works so it isn't functioning.

Thanks.

+3  A: 

Not using jQuery but this works for me, and the approach should be similar

<script type="text/javascript" charset="utf-8">
  var doingStuff = false;
  function doStuff() {
    if (doingStuff) {
      document.getElementById('stuff').innerHTML += '.';
      setTimeout(doStuff, 100);
    }
  }
</script>

<p onmouseover="doingStuff = true; doStuff()" onmouseout="doingStuff = false">
  Mouseover to do stuff
</p>

<p id="stuff">Stuff: </p>

This will add a . to the document every 100ms as long as you are hovering.

Basically, set a boolean value to true on mouseover, and false and mouse out. And dont schedule the next call unless the variable is true. Also, you aren't calling a function every 100ms unless you need to. Meaning nothing is happening until you hover, set the var to true and kick off the repeating function.

Squeegy
The approach seems reasonable. jQuery could clean that up considerably.
Mark
Kind of works, but the doStuff executes atleast twice on each mouseoer which is less than ideal. Easy fix with some conditionals?
Hamid
@Hamid, I have updated my answer to prevent doing stuff twice. It still gets called twice, but moving the if statement prevents it from actually doing any real work.
Squeegy
Thanks. I made the change myself yesterday, fxing the conditionals wasn't a problem. But I have accepted this as the answer now as it matches how I corrected it too. Thanks a lot for the clear answer and subsequent fix.
Hamid