Funkcja setTimeout()
Listing
function drawRectangle(rectangle, context) { context.beginPath(); context.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height); context.fillStyle = 'red'; context.fill(); context.lineWidth = rectangle.borderWidth; context.strokeStyle = 'black'; context.stroke(); }; function animate(rectangle, canvas, context, startTime) { var time = (new Date()).getTime() - startTime; var linearSpeed = 100; var newX = linearSpeed * time / 1000; if (newX < canvas.width - rectangle.width - rectangle.borderWidth / 2) { rectangle.x = newX; } context.clearRect(0, 0, canvas.width, canvas.height); drawRectangle(rectangle, context); setTimeout(function() { animate(rectangle, cv, ctx, startTime); }, 24); }; var cv = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var rectangle = { x : 0, y : 75, width : 100, height : 50, borderWidth : 2 }; drawRectangle(rectangle, ctx); setTimeout(function() { var startTime = (new Date()).getTime(); animate(rectangle, cv, ctx, startTime); }, 24);
Inne aplikacje używające funkcji setTimeout()