www.webdeveloper.com
+ Reply to Thread
Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2006
    Posts
    3

    Change Image every 4 seconds in Javascript

    Hello all,

    The code below supposed to change the displayed picture from pic1 to pic2 in 4 seconds after pressing the 1st picture, when i execute it after 4 seconds there is an error saying "Pic is Undefined", please help me find the problem?
    Thanx.

    Code:
    <head>
        <script type="text/javascript">
            function TimerSwitch(pic) {
                TimerRunning=true;
                var timer = setTimeout('SwitchPic(pic)', 4000);  
            }
            function SwitchPic(pic) {
                pic.src = "pic2.jpg";
            }
        </script>
    </head>
    <body>
        <img class="switch" src="pic1.jpg" onclick="TimerSwitch(this)" />
    </body>
    </html>

  2. #2
    Join Date
    Feb 2010
    Posts
    184
    Timeout executes the code globally so pic isn't defined. You need closure.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">
          function TimerSwitch(pic) {
            TimerRunning=true;
            var timer = setTimeout(function() { SwitchPic(pic) }, 4000);
          }
          function SwitchPic(pic) {
            pic.src = "pic2.jpg";
          }
        </script>
      </head>
      <body>
        <img class="switch" src="pic1.jpg" alt="something" onclick="TimerSwitch(this)" />
      </body>
    </html>

  3. #3
    Join Date
    Feb 2006
    Posts
    3
    Thank you for the quick answer, it works perfectly

  4. #4
    Join Date
    Aug 2007
    Posts
    3,764
    Code:
            function TimerSwitch(pic) {
                TimerRunning=true;
                var timer = setTimeout(function () {SwitchPic(pic);}, 4000);  
            }
    Has to be global if you pass a string to setTimeout.

    EDIT: Answered already, didn't see that.
    Great wit and madness are near allied, and fine a line their bounds divide.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center



Recent Articles