codin freak
codin freak

Reputation: 287

Jquery setTimeout inside a setTimeinterval not working

I have a setinterval that moves bulldozer from the right to the left.

In the jsfiddle below, the setInterval must stop itself after 5 seconds. (used a settimeout and clearinterval for that) but it's not working. Can anyone help me?

http://jsfiddle.net/B5MKj/11/

var gameover;
gameover = setInterval(function () {
    setTimeout(function () {
         clearInterval(movingbulldozer);
    }, 55000);
}, 10);

Upvotes: 2

Views: 1207

Answers (2)

Patsy Issa
Patsy Issa

Reputation: 11303

You had a typo in your fiddle, updated fiddle, if works just fine, but instead of 5000 ms you had 55000ms set for the timeout.

 setTimeout(function () {
   clearInterval(movingbulldozer);
 }, 5000);

Upvotes: 1

ReSpawN
ReSpawN

Reputation: 689

In your example, movingbulldozer is undefined. If you're trying to clear the interval, clear the interval with the right reference. In your example, this would be clearInterval(gameover);

The problem with your example is that every 10 ms you're adding a timeout to the DOM which clears the interval.

var timeout, interval, date,
    i = 0;

$(document).ready(function() {
    interval = setInterval(function() {
        date = new Date();
        i++;

        $('#debug').html('Interval parsed at '+date.getTime()+', interval #'+i);

        if (i >= 100) { // According to your example
            $('#debug').html('Starting timeout...');

            timeout = setTimeout(function() {
                $('#debug').html('Timed out');
            }, 5000);

            clearInterval(interval);
        }
    }, 10);
});

Check out my example, see if it helps. :)

http://jsfiddle.net/faqq5/

Upvotes: 0

Related Questions