Why Do My Images Keep Swapping??

Discussion in 'Javascript' started by Prisoner at War, Apr 12, 2008.

  1. Hi, Everybody,

    The fucntion below is called by an onLoad <img> attribute, and it is
    supposed to replace the original image, after three seconds, with
    another image. This second image shouldl be replaced, after eight
    more seconds, with the original image.

    For some reason, JavaScript keeps swapping the images back and forth
    endlessly -- and not even properly counting out all the seconds
    specified, after the first time swapping! What's going on???


    function mytest() {

    setTimeout("window.document.test.src='../images/substitute.jpg';",
    3000);
    setTimeout("window.document.test.src='../images/original.jpg';",
    8000);
    }
     
    Prisoner at War, Apr 12, 2008
    #1
    1. Advertisements

  2. * Prisoner at War wrote in comp.lang.javascript:
    Loading each replacement image successfully also counts as "load" and so
    the code in the onload attribute is evaluated again and again. There are
    several ways to break a cycle like this, one is to simply store in a va-
    riable whether this is the first swap, and if not, skip the setTimeout.
     
    Bjoern Hoehrmann, Apr 12, 2008
    #2
    1. Advertisements

  3. Hmm...thanks; interesting...I just can't "feel" the logic of
    JavaScript deciding to count each image swap as an "onLoad" in
    itself...I thought JavaScript would just read and execute each line in
    order and then, when it ran out of lines to execute, it would just
    stop....
     
    Prisoner at War, Apr 12, 2008
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.