1

Possible Duplicate:
setInterval only runs once?

Before I proceed let me say as a designer logic comes difficultly, so I appreciate you bearing with my ignorance.

I am making a simple slider, and I would like it so that when the user moves the picture with their mouse the program can make note of the distance covered in the last second before mouseup(), so that in turn I can calculate how much the picture has to travel to simulate as though it was swiped.

I've got my base event handlers as so:

$('.testdiv').mousedown(function(){

    pretestFunction();

    //mouse is pressed
    mousepressed = 1;

    //set first X point
    prevX = event.pageX;


}).mouseup(function(){

    //get stop X point
    stopX = event.pageX;
    mousepressed = 0;

});

pretestFunction calls setInterval, like so:

function pretestFunction(){
    window.setInterval(testFunction(), 1000);
}

testfunction():

function testFunction(){
    console.log('1 second');
}

My problem is that the set interval function is only called once, and not once every second like I am trying to get it to do. What am I doing wrong?

Community
  • 1
  • 1
styke
  • 2,116
  • 2
  • 23
  • 51

1 Answers1

5
window.setInterval(testFunction(), 1000);

should be

window.setInterval(testFunction, 1000);

In the first, you are passing the value of calling testFunction (which happens to be undefined, but thats not important)

In the second you would be passing the value of testFunction (i.e. a function, which is what you want.)

Jacob Parker
  • 2,546
  • 18
  • 31
  • 1
    Aha! A small but costly mistake. Thank you. On a sidenote, how can I then pass variables to the function called using setInterval? – styke Feb 02 '13 at 15:04
  • 3
    if you have a function foo that takes an integer argument you can do: setInterval(function() { foo(42); }, 1000); i.e. pass an anonymous function that calls your function with the values you want. – Jacob Parker Feb 02 '13 at 15:06