0

I have created this code to random my divs when I'm clicking on the button:

$('button').click(function(){ 
              setInterval(function(){ 

                var firstdiv = $('.roll div:first');
                var lastdiv = $('.roll div:last');

                firstdiv.insertAfter(lastdiv);
                firstdiv = firstdiv.next();  

               }, 100);
           });

How can I stop it after 5 seconds for example?

My Example: http://jsfiddle.net/L0aaxqrs/

lambada
  • 29
  • 1
  • 9

1 Answers1

2

You clear it inside a timeout

$(document).ready(function () {
    $('button').click(function () {
        var interval = setInterval(function () {

            var firstdiv = $('.roll div:first');
            var lastdiv = $('.roll div:last');

            firstdiv.insertAfter(lastdiv);
            firstdiv = firstdiv.next();

        }, 100);

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

    });
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388