Search code examples
jqueryimagehtmltimer

How to stop an image flickering in an ajax timer


I have this in markup.

<%@ Page Title="" Language="C#" MasterPageFile="~/Cloud.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Cloud_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
    <asp:Button ID="btnPlay" runat="server" Text="Play" ClientIDMode="Static" />
    <div id="divPlayer" style="width: 352px; height: 288px;">hello
    </div>

    <script type="text/javascript">
        $("#btnPlay").click(function () {
            Play();
        });
        var $theDiv = $("#divPlayer");
        var request;    
        var _currentFrame = 1;

        setInterval(function Play() {
            if (request) request.abort();
            request = $.ajax({
                type: "POST",
                url: "Default.aspx/GetNextFrame",
                data: JSON.stringify({
                    CurrentFrame: _currentFrame
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if (msg.d != "") {
                        $("#divPlayer").css("backgroundImage", "url(" + msg.d + ")"); 
                        _currentFrame++;
                    }
                },
                error: function (msg) {
                    var r = jQuery.parseJSON(msg.responseText);
                    alert(r);
                }
            });
        }, 100);     
    </script>
</asp:Content>

In my code behind I have this:

[WebMethod]
public static string GetNextFrame(int CurrentFrame)
{
 if (HttpContext.Current.Session["Clip"] == null)
{
HttpContext.Current.Session["Clip"] = Directory.GetFiles(@"C:\Portal\Catalogues\000EC902F17F\3\2013\10\6\10\657c2728-c6a5-41d8-bbdf-1815f5b37d5d");
}
string[] _files= (string[])  HttpContext.Current.Session["Clip"];
if (CurrentFrame < _files.Length)
{
string _filename = new FileInfo(_files[CurrentFrame]).Name;
string _imgURL = "\" A URL\"";
return _imgURL;
}
return "";
}

The image 'plays' but there is a flicker. I thought the solution was to just update the URL of the div background to solve this? I have, and I still get a flicker.


Solution

    1. Check the size of your image. The larger the size the more it will take to render and the larger the flicker.
    2. If you can, load all the images first so that you don't have to go server side to get the next image. Might improve on perceived performance.
    3. Try using two divs and hide/show them in an alternating fashion. This might eliminate flicker due to the primary div reloading.

    edit

    Using C# code, you could build an animated gif and return that instead of a series of frames.

    This might help; how to create an animated gif in .net