David Jones
David Jones

Reputation: 10219

Simple nested setTimeout() only runs once (JavaScript)

For some reason my galleryScroll() function only runs once, even though the function calls itself using setTimeout(). I'm thinking the issue may be related to scope, but I'm not sure:

http://jsfiddle.net/CYEBC/2/

$(document).ready(function() {
    var x = $('#box').offset().left;
    var y = $('#box').offset().top;
    galleryScroll();

    function galleryScroll() {
        x = x + 1;
        y = y + 1;
        $('#box').offset({
            left: x,
            top: y
        });
        setTimeout('galleryScroll()', 100);
    }
});​

The HTML:

<html>
<head>
</head>
<body>
    <div id="box">
    </div>
</body>
</html>​

Upvotes: 1

Views: 3275

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270609

The function galleryScroll() isn't defined in the correct scope to be evaluated in setTimeout(). If you want it running in a loop, call it in setInterval() after the function.

$(document).ready(function() {
    var x = $('#box').offset().left;
    var y = $('#box').offset().top;
    galleryScroll();

    function galleryScroll() {
        x = x + 1;
        y = y + 1;
        $('#box').offset({
            left: x,
            top: y
        });
    }
    // Call in setInterval() outside the function definition.
    // Note also, I've changed the eval string 'gallerySroll()' to the function reference galleryScroll
    setInterval(galleryScroll, 100);
});​

Here is the updated fiddle.

Upvotes: 2

RestingRobot
RestingRobot

Reputation: 2978

Your problem is how you're calling the galleryScroll() function in your setTimeout. Change that line to this:

   setTimeout(galleryScroll, 100);

The result: http://jsfiddle.net/CYEBC/12/

Note: I'm not sure if this is the desired behavior, but it's what happens when your code is called properly.

Upvotes: 1

Related Questions