Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8831349
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T08:17:23+00:00 2026-06-14T08:17:23+00:00

I am replacing an image on a page on a timer using setInterval in

  • 0

I am replacing an image on a page on a timer using setInterval in javascript (it’s a stats graph that needs to be up to date).

I am using the following code:

var tid = setInterval(mycode, 20000);
function mycode() {
    var theDate = new Date();
    var mili = theDate.getUTCDate() + theDate.toLocaleTimeString() + theDate.getMilliseconds();
    var img = $('<img />')
        .attr('src', '@Url.Action("Chart", "Home", new {ForceNoCache = "theDate"})')
        .attr('id', 'GraphImage')
        .load(function () 
        {
            if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) 
            {
                alert('broken image!');
            } 
            else 
            {
                $('#GraphImage').replaceWith(img);
            }
        });
        img.attr('src', img.attr('src').replace("theDate", mili));
}

The image is currently just sitting in a div on the page like this:

    <div style="float:left;margin-right:20px">
    <img id="GraphImage" alt="Graph of Results" src="@Url.Action("ChartImage", "Home")" /> 
  </div>

This code works and replaces the image every 20 seconds – however, even though I’m using the .load function and not replacing the image until it is fully loaded, I still get an annoying little flicker as the browser swaps the image over.

How would I go about using a jQuery fade transition/animation to smoothly swap over the two images? Ideally I’d like a way to do this without needing too much in the way of additional markup gumph or css limitations on how the image can be styled and positioned in the page.

Similar to this question: Javascript Image Reloading; flickers

However I am already using the accepted answer on this question, and still getting flicker.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T08:17:24+00:00Added an answer on June 14, 2026 at 8:17 am

    Every time mocode() fires, you appear to create a new <img /> and replace the previous one. You will get a much smoother effect by reusing the same <img> – just change its src.

    I’m not sure exactly how your code works so it’s difficult to be certain but I think you need something like this :

    function graphError() {
        alert('Graph: reload failed');
    }
    var $graphImg = $("#GraphImage").on('error', graphError);
    var tid = setInterval(mycode, 20000);
    function mycode() {
        var theDate = new Date();
        var mili = theDate.getUTCDate() + theDate.toLocaleTimeString() + theDate.getMilliseconds();
        $.ajax({
            url: '@Url.Action("Chart", "Home", new {ForceNoCache = "theDate"})',
        }).done(function(srcURL) {
            $graphImg.attr('src', srcURL.replace("theDate", mili));
        }).error(graphError);
    }
    

    You may need to build the url differently, and with a little thought the error message could be made more specific.

    EDIT

    Tyco, your solution looks good and if it works maybe you will want to stick with it. Meanwhile I’ve been playing with a similar idea but dramatically different code centered around jQuery’s Deferreds. These are a little mind-blowing if you’ve not used them but are very useful when you have asynchronous tasks.

    In your case, you have three sequential asynchronous tasks, fetching the graph URL, loading the graph image, and fading out the previous graph to reveal the new version.

    Coding this is fairly straightforward but the code needs to be error-tolerant – in particular it needs to cater for server responses (URL and the image itself) arriving back in the wrong order or after the next firing of the setInterval. Deferreds help enormously by providing the means to cancel function chains established at the previous iteration.

    With a 20 second interval, there shouldn’t be a problem, but one day the internet/server may be running exceptionally slowly or you may decide to reduce the interval.

    Unless you have used Deferreds before, the code below will look very alien but, barring errors on my part, it should do the job.

    Javascript:

    $(function() {
        var $graphImg1 = $("#GraphImage1");
        var $graphImg2 = $("#GraphImage2");
    
        var promises = {
            fetchGraphUrl: null,
            loadImg: null,
            fadeOut: null
        };
    
        var graph_errors = {
            threshold: 5,//set low for testing, higher in production environment.
            count: 0
        };
        var interval = 5;//seconds
    
        $graphImg2.on('error', function() {
            if(promises.loadImg) {
                promises.loadImg.reject();
            }
        }).on('load', function() {
            if(promises.loadImg) {
                promises.loadImg.resolve();
            }
        });
    
        function graph_fetchURL(milli) {
            if(promises.fetchGraph) {
                promises.fetchGraph.reject(milli, 'fetchURL', 'timeout');
            }
            var dfrd = promises.fetchGraph = $.Deferred().fail(function() {
                jqXHR.abort();
            });
            var jqXHR = $.ajax({
                url: '@Url.Action("Chart", "Home", new {ForceNoCache = "theDate"})'
            }).done(function(srcURL) {
                dfrd.resolve(milli, srcURL);
            }).fail(function(jqXHR, textStatus, errorThrown) {
                dfrd.reject(milli, 'ajax', textStatus);
            });
            return dfrd.promise();
        }
    
        function graph_loadImg(milli, srcURL) {
            if(promises.loadImg) {
                promises.loadImg.reject(milli, 'loadImg', 'timeout');
            }
            //An extra deferred is needed here because $graphImg2's handlers don't know about milli.
            var dfrd = $.Deferred();
            promises.loadImg = $.Deferred().done(function() {
                dfrd.resolve(milli);
            }).fail(function() {
                dfrd.reject(milli, 'loadGraph', 'load error');
            });
            $graphImg2.attr('src', srcURL.replace("theDate", milli));
            return dfrd.promise();
        }
    
        function graph_fade(milli) {
            if(promises.fadeOut) {
                promises.fadeOut.reject(milli, 'fade', 'timeout');
            }
            promises.fadeOut = $.Deferred();
            $graphImg2.show();
            $graphImg1.fadeOut('fast', function() {
                promises.fadeOut.resolve(milli);
            });
            return promises.fadeOut.promise();
        }
    
        function graph_swap() {
            $graphImg1.attr('src', $graphImg2.attr('src')).show();
            $graphImg2.hide();
        }
    
        function graph_error(timestamp, phase, txt) {
            var txt = txt ? (' (' + txt + ')') : '';
            console.log(timestamp + ': fetchGraph failed in the ' + phase + ' phase' + txt);
            if(++graph_errors.count >= graph_errors.threshold) {
                clearInterval(tid);
                console.log('fetchGraph errors exceeded threshold (' + graph_errors.threshold + ')');
            }
            return $.Deferred().promise();//an unresolved, unrejected promise prevents the original promise propagating down the pipe.
        }
    
        function fetchGraph() {
            var now = new Date();
            var milli = now.getUTCDate() + now.toLocaleTimeString() + now.getMilliseconds();
            graph_fetchURL(milli)
                .pipe(graph_loadImg, graph_error)
                .pipe(graph_fade, graph_error)
                .pipe(graph_swap, graph_error);//this .pipe() chain is the glue that puts everything together.
        }
        fetchGraph();
        var tid = setInterval(fetchGraph, interval * 1000);
    });
    

    CSS:

    #graphWrapper {
        position: relative;
        float: left;
        margin-right: 20px;
    }
    #GraphImage, #GraphImage2 {
        position: absolute;
        left: 0;
        top: 0;
        width: XXpx;
        height: YYpx;
    }
    #GraphImage2 {
        display: none;
    }
    

    HTML:

    <div id="graphWrapper">
        <img id="GraphImage1" alt="Graph of Results" src="" /> 
        <img id="GraphImage2" alt="" src="" /> 
    </div>
    

    As you will see, everything is organised into a bunch of fairly concise functions, each a variation on a common theme, namely :-

    • to reject any outstanding task of the same kind from a previous iteration
    • to create a deferred that can be rejected at the next iteration
    • to perform the task itself
    • to return a promise derived from the Deferred

    The last task, graph_swap(), is straightforward and the error handler graph_error() is slightly different.

    See comments in code for further details.

    In addition to handling errors and tardy server responses, a MAJOR advantage of this approach is that the main iterator function, fetchGraph() becomes VERY simple. The really clever line is a set of chained pipe() commands which sequence the tasks and route any errors to the error handler.

    I have tested this as much as I can and think that, like your own solution, it will give a smooth transition.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The documentation page for Camera.setDisplayOrientation contains the following code sample stating that using it
I'm replacing some text with cufon on my page and I'm using jquery stylish
I am using the following code in order to add images to an existing
Replacing the Special Character using Perl while i am doing this . I got
I am replacing some deprecated Javadoc annotation in code I am unfamiliar with. Most
I'm interested in replacing an aging control we use in our project that is
I'm converting the first page of a docx file to an image in twoo
I always thought that replacing the <center> tag with <div style=text-align:center;> will get me
I'm using jquery + the accordion plugin. That's working great. Now, I want another
I'm using a wonderful plugin computedstyle.js that gets the computed style of objects. It

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.