0

I need to call a function periodically with setInterval and passing parameters to it. At the same time, I need to clear the interval inside the function that's being called when the mouse is moved.

So I'm trying this:

var timer = setInterval(function(x,y){ // When I use this, x and y are undefined.

  /*
   Code
  */

  document.getElementById("wholeDocument").onmousemove=clearInterval(timer);

  }, 50);

The idea is to know how to use setinterval with a clearInterval inside and being able to pass parameters.

I would appreciate any help.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • how will you get x and y – closure Dec 16 '12 at 17:58
  • How do you intend to use it. Is it required? – closure Dec 16 '12 at 18:01
  • x, and y are two variables with the coords of the mouse. that's actually working fine. It's something like this. var e = event; var x=e.clientX; var y=e.clientY; – user1770660 Dec 16 '12 at 18:02
  • You may not want to bind mousemove in every interval function execute. It should be outside – closure Dec 16 '12 at 18:03
  • What I'm trying to do is: There are 3 divs and they move towards the mouse pointer. So when the pointer is at let's say (150,300) the setInterval calls the function that makes the divs move. So if the mouse changes coords, the clearInterval triggers and it starts all over again. So x and y are the mouse coords everytime. – user1770660 Dec 16 '12 at 18:06
  • Got it. You would need to record and remember the x & y. Will edit my code. – closure Dec 16 '12 at 18:09
  • Well actually, x and y are being refreshed all the time because each time you move your mouse over the document it gets the mouse coords. But I just can't pass the parameters when I define the function inside setInterval, and I also need to do that to be able to clear it afterwards. – user1770660 Dec 16 '12 at 18:18
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/21226/discussion-between-raghavv-and-user1770660) – closure Dec 16 '12 at 18:20

2 Answers2

0

Apart from the concept which could possibly be improved depending on what you're trying to achieve, this line

document.getElementById("wholeDocument").onmousemove=clearInterval(timer);

should be

document.getElementById("wholeDocument").onmousemove = function(e) { clearInterval(timer); }
Damp
  • 3,328
  • 20
  • 19
0
var timer = null;
document.getElementById("wholeDocument").onmousemove= function(evt) {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
    x = evt.clientX;
    y = evt.clientY;
    var timer = setInterval(function() { fnTimer(x, y); }, 50);
};

function fnTimer(x, y) {
  // your code here
}
closure
  • 7,412
  • 1
  • 23
  • 23