Valerie Meunier

Valerie Meunier

  • 827
  • 693
  • 75.8k

how to pass parameter to function in setTimeout?

Aug 28 2022 4:35 PM

Hi

I try to move an image vertically from + 450px to -450px. But i want to pass a parameter (the number of times it must run) to the function. The problem is the function into SetTimout. With this code below, the image doesn't move.

Thanks

V

 <img id="clem" src="fotos/clem.jpg" style="position: relative; ondblclick="go(2)"  /> 

var clem = document.getElementById("clem").style;
var x = 0;
var y = 0;
    function go(z)
    {
        y += 1;
        if (y < z * 900) // number of times to run
        {
            if (x < 450)
            {
                x += 1;
                clem.top = x + "px";
                if (x == 450)
                {
                    x = -450;
                }
                setTimeout(go(z), 10); // nothing happens

               //  setTimeout(go, 10);  It doesn't work either

               //    setTimeout("go(z)", 10); or  setTimeout('go(z)', 10); both moves 1px.
            }
        }
        else
        {
            clem.top = "0px";
        }
    }


Answers (2)