3
function SlideShow(area)
    {
        var SlideImg = new Array('img1', 'img2');
        var SlideArea = document.getElementById(area);
        for(i=0;i<SlideImg.length;i++)
        {
            var html = '<img src="images/room/' + SlideImg[i] + '.jpg" id="' + SlideImg[i] + '" class="not-active" />';
            SlideArea.innerHTML += html;
        }
        var a = 0;
        function RunSlide()
        {
            document.getElementById(SlideImg[a]).className = 'active';
            a++;    
        }
        var run = setTimeout('RunSlide()', 5000);
    }

This function not working after I add the setTimeout() method there. Can anybody help me?

Ega Rana
  • 69
  • 4
  • 2
    an aside, I'd make sure in your for loop to declare 'var i = 0' to avoid implicit globals. – Thomas Thorogood Jul 14 '12 at 14:40
  • 1
    You're passing a string to `setTimeout()` and that's generally a bad way to go. The string will eventually be evaluated in the global scope, and in that context `RunSlide` will not be defined. By passing a **reference** to the function instead, the timeout sholuld work. – Pointy Jul 14 '12 at 14:40

1 Answers1

9

Just change it to:

var run = setTimeout(RunSlide, 5000);

The reason is: when you pass a string to setTimeout() it is evaluated in global context - where RunSlide is not visible, because it is local.

Passing a string to setTimeout() is never a good idea, here you have one reason.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • It doesn't work, or maybe the setTimeout() method cannot work if I put it in a function? – Ega Rana Jul 14 '12 at 14:43
  • @EgaRana: can you wrap your code in a jsFiddle? How it *doesn't* work? Maybe you wanted to run your code in a "loop" (`setInterval()`)? – Tomasz Nurkiewicz Jul 14 '12 at 14:44
  • It's solved with your code, sorry it's my mistake before to put your code in wrong place. But what is the difference beetwen setTimeout(RunSlide, 5000) and setTimeout('RunSlide()', 5000)? I was read, to call a function it must call the function name in string. – Ega Rana Jul 15 '12 at 07:00
  • @EgaRana: check out http://stackoverflow.com/questions/10312963 and https://developer.mozilla.org/en/DOM/window.setTimeout#Passing_string_literals – Tomasz Nurkiewicz Jul 15 '12 at 08:26