Damien
Damien

Reputation: 333

Using stop() with jquery to launch a function only one time

I don't understand the use of stop() element in jquery. In this example, i try to open a div when the user launch the myfunction function (for example by clicking on a trigger) But if you click several time, #mydiv desapears anyway, without waiting 3 seconds, because it close 3 second after your first click.

function myfunction(hello)
 {
   $( "#mycontener" ).html( hello );
$( "#mydiv" ).stop( true, true ).slideDown( 250, function() {
setTimeout(function() {
  $("#mydiv").slideUp( 250 );
}, 3000);
});
};   

Is it clear enough ? Thanks

Upvotes: 0

Views: 34

Answers (1)

Esteban Felix
Esteban Felix

Reputation: 1561

You will need to clear the timeout to prevent it from happening on future calls. Something like this:

(function () {
    var handle;
    function myfunction(hello) {
        clearTimeout(handle);

        $("#mycontener").html(hello);
        $("#mydiv").stop(true, true).slideDown(250, function () {
            handle = setTimeout(function () {
                $("#mydiv").slideUp(250);
            }, 3000);
        });
    }

    window.myfunction = myfunction;
})();

Upvotes: 1

Related Questions