Matthew Ciaramitaro Matthew Ciaramitaro - 6 months ago 42
Javascript Question

Jquery repeat functions

I am trying to use jquery to program pong. I want the ball to be moving indefinitely but I don't know how to get my event to occur more than once. I am using

keydown
and
keyup
for moving the barrier at the bottom and want a way that moves the ball and allows me to continue moving the two barriers.

I have a function that determines which way to move the ball, and i want to repeat that function indefinitely.
I tried
moveball().repeat('Infinity');
and
$(".ball").moveball().repeat('Infinity');


moveball is defined as such:

function moveball(){
if(balldirection.search("down") !== -1){
$(".ball").animate({top: '+='+ 40 + 'px'},0);
}
else if(balldirection.search("up") !== -1){
$(".ball").animate({top: '-=' +40 + 'px'},0);
}
if(balldirection.search("left") !== -1){
$(".ball").animate({left: '-=' +20 + 'px'},0);
}
else if(balldirection.search("right") !== -1){
$(".ball").animate({left: '+=' +20 + 'px'},0);
}
}

Answer

var loop = setInterval(moveball, 50);

this will repeat moveball every 50 milliseconds. call clearInterval(loop) to stop it.