Understanding Javascript asynchronous setInterval in canvas -
the following code creates canvas ball @ centre when init()
method invoked using setinterval
. when keydown()
event fired ball moves on x , y axis (depending on key user has pressed). struggle understand happens when key pressed.
does setinterval
stop when key pressed update key value (keyleft
, keyright
, etc) , resumes , takes updated values consideration
or
does code inside key event execute while setinterval
in progress?
i 've read setinterval
asynchronous while key events synchronous , since javascript single threaded second option can't true, right? use knowledge on one..
<canvas id="canvas" style="border: 1px solid black" width="400" height="400"></canvas> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> var ball = { positionx: 200, positiony: 200, keyleft: false, keyright: false, keyup: false, keydown: false, init: function() { this.canvas = document.getelementbyid('canvas'); this.ctx = this.canvas.getcontext('2d'); setinterval(ball.draw, 10); }, circle: function (x, y, fill) { this.ctx.beginpath(); this.ctx.arc(x, y, 20, 0, math.pi * 2, false); if (fill) { this.ctx.fill(); } else { this.ctx.stroke(); } }, draw: function() { ball.ctx.clearrect(0, 0, 400, 400); if (ball.keyleft) ball.positionx -= 5; else if (ball.keyright) ball.positionx += 5; if (ball.keyup) ball.positiony -= 5; else if (ball.keydown) ball.positiony += 5; ball.circle(ball.positionx, ball.positiony, true); } } ball.init(); $('body').keydown(function (e) { var key = e.keycode; if (key == 37) { ball.keyleft = true; } else if (key == 39) { ball.keyright = true; } if (key == 38) { ball.keyup = true; } else if (key == 40) { ball.keydown = true; } }); </script>
javascript (in browsers) event-driven language. of time, nothing being executed. when event occurs , script has registered listener particular type of event, event placed queue. if part of script being executed, not interrupted - rather, when completes, browser pull next event queue , start executing registered handler it.
in code, registering 2 kinds of events: timer events (implicitly, using setinterval
) , keydown
events (explicitly, using jquery, uses addeventlistener
). when timer event fires, ball.draw
method executed. if keydown
event arrives while running, waits in queue until ball.draw
finishes. dispatched handler function assigned. , vice versa: if keydown
handler in progress, 10 milliseconds pass, , timer event occurs, timer event has wait until keydown
handler completes. 1 reason why javascript timers inherently imprecise.
short version: keydown
handler can execute in between executions of ball.draw
. changes makes variables used both functions visible ball.draw
on next invocation.
Comments
Post a Comment