<!DOCTYPE html>
<html>
<head>
    <script src="../../resources/js-test-pre.js"></script>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        description("Ensure the image frame duration is respected even if the frame finishes decoding early.");
        jsTestIsAsync = true;

        internals.clearMemoryCache();

        var image = new Image;
        image.onload = imageLoaded;
        image.src = "resources/animated-red-green-blue.gif";

        function imageLoaded()
        {
            if (!window.internals)
                return;
            internals.setImageFrameDecodingDuration(image, 0.040);
            internals.settings.setAnimatedImageDebugCanvasDrawingEnabled(true);
            drawImage();
            drawLoop();
        }

        function drawImage()
        {
            if (drawImage.count == undefined)
                drawImage.count = 0;
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
            return ++drawImage.count;
        }
                
        function drawLoop()
        {
            // 1st time the image is drawn, time = 0, current_frame = 0
            // 2nd time the image is drawn, time = 50, current_frame = 1
            // 3rd time the image is drawn, time = 100, current_frame = 2
            setTimeout(function() {
                if (drawImage() == 3) {
                    shouldBe("internals.imageFrameIndex(image)", "2");
                    finishJSTest();
                } else
                    drawLoop();
            }, 50);
        }
    </script>
    <script src="../../resources/js-test-post.js"></script>
</body>
</html>
