Skip to content Skip to sidebar Skip to footer

Stop Loop Function On A Button's Click

I've a series of arrays which I'm displaying one after another using jquery loop. Check JSFiddle Demo. Now I want to stop it when a user click on 'stop it now' button. HTML: <

Solution 1:

One solution is to use .stop(true, false). Doing this will clear the queue and without executing the pending functions.

$("button").on("click", function() {
    $text.stop(true, false);
})

Updated Fiddle

Solution 2:

Use a flag. Try this:

var flag = false;

$(".stop button").click(function(){
    flag=true;
});
functionloop ( delay ) {
    $.each( items, function ( i, elm ){
        $text.delay( delay*1E3).hide();
        $text.queue(function(){
            $text.html( items[i] );
            $text.dequeue();
        });
        $text.show();
        $text.queue(function(){
            if ( i == items.length -1 ) {
                loop(delay);   
            }
            $text.dequeue();
        });
        if(flag) break;
    });
}

Solution 3:

If you change the logic you use to implement a timer it makes the code much simpler and also means you can simply call clearInterval on the timer to stop the text changing. Try this:

$(document).ready(function() {
    var items = ["Answer Two", "Answer Three", "Answer Four", "Answer Five", "Answer Six", "Answer One"],
        $text = $('#div1'),
        delay = 200, // miliseconds
        itemIndex = 0;

    var interval = setInterval(function() {
        $text.text(items[itemIndex % items.length]);
        itemIndex++;
    }, delay);

    $('button').click(function() {
        clearInterval(interval);
    })
});

Example fiddle

Solution 4:

I added a parameter called "stopLoop" which is being initialized as false. Once button is clicked that parameter becomes true and stops the loop. Here: http://jsfiddle.net/fcLso5c9/9/

$(document).ready(function() {
var stopLoop = false;

$("button").click(function(){stopLoop = true;}); var items = ["Answer Two", "Answer Three", "Answer Four", "Answer Five", "Answer Six", "Answer One"], $text = $( '#div1' ), delay = .2; //seconds

function loop ( delay ) {
    if (stopLoop) return;
    $.each( items, function ( i, elm ){
        $text.delay( delay*1E3).hide();
        $text.queue(function(){
            $text.html( items[i] );
            $text.dequeue();
        });
        $text.show();
        $text.queue(function(){
            if ( i == items.length -1 ) {
                loop(delay);   
            }
            $text.dequeue();
        });
    });
}

loop( delay );

});

You can use almost the same code to have a start/stop functionality

Post a Comment for "Stop Loop Function On A Button's Click"