View Full Version : a loop that only runs while mouse is down?

11-03-2004, 10:29 PM
Hi! Well, Im doing a simple game using javascript in which you shoot a sling shot. One of the things I plan on doing is that when you hold your left mouse button down, it is as if you were puling the ruber band on the sling shot; so, the longer you hold the mouse button down, the farther you are pulling the band. What Im trying to do is make a loop of some sort that will keep track of the time you hold your mouse button down, and when you release the mouse button, the loop will stop.
this is what I have for now:

function pull(nn,xx){ //dont worry with the 'xx'... its for later purposes
if(nn==1){ //if nn = 1, the bullet moves
hhh=document.getElementById("bullet") //the ("bullet") is a <div> tag containing the image for the bullet
setTimeout("pull(1,xx)",500) //this is supposed to do the loop
<body onmousedown="pull(1,event.clientX)" onmouseup="pull(0,event.clientX)"> //again... dont worry with the 'clientX'...

what happens is that the "bullet" does move, but only if I keep pressing the mouse... I want it to move alone until the mouse is released. Actually I dont want the bullet to move yet, but if you show me the correct way to make the loop, I will know how to deal with the rest...


11-04-2004, 10:40 AM
The first argument of setTimeout(), the function called, has to be a string. Thus, if you wanna use passed parameters, you must consider something like this:


11-04-2004, 03:03 PM
hey thanks! Im going to try that. :D

11-04-2004, 05:18 PM
will do it for sure! :thumbsup: