0

I got 5 sprites( 5 blocks, each next smaller than previous). And they drawing too fast. how to right use new Date(), getMilliseconds or other methods for timer that would draw with some delay?

For ex.

for ( i = 0; i < 5; i ++ ) {
    xxx.drawImage(sprite, i, etc);
}
mutant_america
  • 738
  • 6
  • 18

1 Answers1

0

Use setInterval() or setTimeout() to set a timer. But you should notice a subtle difference between these 2 functions due to single threaded nature of javascript. Let's look at the example:

setTimeout(function test() {
   //your code
   setTimeout(test, 100);
}, 100);

setInterval(function() {
     //your code
}, 100);

These 2 blocks of code appear to be the same, but that's not the case due to single-threaded nature of javascript.

  • With setInterval(): if your code is busy executing and takes long time to complete. The next intervals may fire while your code is still executing and these intervals will be queued up. In the end, you may end up with some handlers running in succession without any delay

  • With setTimeout(): the next interval is only set to be fired when you're current code has finished. This guarantee that the next execution will never be less than the interval (100 in this case), only equal to or longer.

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • thats would not work in a cycle function main() { setTimeout(function test() { console.log('test'); setTimeout(test, 1000); }, 1000); requestAnimFrame(main); } timeout executes 1 time after 1000ms and then function executes withiout delay... sorry for that mess... cant answer, just comment( – mutant_america Aug 01 '13 at 17:51
  • @Rss_game_dev: you should not do it like this. Try: `function main() { setTimeout(function test() { console.log('test'); requestAnimFrame(variable); setTimeout(test, 1000); }, 1000); }`. I assume that the `requestAnimFrame` is your logic to draw image, change the parameter to another name (`variable` as in the example) to avoid name conflicting with the `main` function – Khanh TO Aug 02 '13 at 02:10
  • I just tried to do ur code but RequestAnimationFrame in brackets needs the name of function which would periodically execute. so function main() { RequestAnimationFrame(main) } thats works but how in this function call 'test' each time after 1000ms. not once – mutant_america Aug 02 '13 at 05:45
  • @Rss_game_dev: you should create another function and call it `requestAnimFrame(variable);` (in this case I define the function as `variable`) – Khanh TO Aug 03 '13 at 02:40