0

Somehow i did my research and found out javascript is single threaded !. I've been trying to figure out , how to make animation via for loop in javascript.

This is what i've done so far. I'm trying to draw an object on a canvas using javascript. It run the loop it doesn't go step by step. It's just run the loop and draw once instead of 10 times and it ignores the timeout function.

In a single instance , it drew (P/S. Ignore the multiple version cause i was testing it so i removed the context.clearRect(0, 0, context.canvas.width, context.canvas.height); :

Image

JS:

   // down button click
   down.onclick = function() {
      if (!imgLoaded) return;
      flag=false;
      setTimeout(function() {
  for(var i = 0; i < 15 ; i++) {
    posY += 10;
     context.drawImage(img, posX, posY );
  }}, 9);
  // call next step

1 Answer 1

1

That's not the way setTimeout works. The way you wrote it, setTimeout calls its first parameter one time, after 9 ms, then loops with no delay.

You could use the setInterval function (don't forget to removeInterval after the 15th iteration) if you want to be called a regular interval.

Note that in both case (setTimeout, setInterval), given delay is only indicative.

What you might want to use is the Window.requestAnimationFrame() function, which is the usual way to do animation in the browser.

Sign up to request clarification or add additional context in comments.

2 Comments

setInterval has no luck either :(
If you just replaced settimeout by setInterval in your code, that sure won't work better (will repeats the 15 iterations every 9ms). Please read setTimeout setInterval documentation and Window.requestAnimationFrame exemples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.