admin管理员组

文章数量:1394049

I have

<script>
function myfunc(){
alert("show this alert in 5000ms after toggleClass executed")
//some code goes here
}

$(document).ready(function(){
    $('.mybtn').on('click',function(){
        $('#mydiv').toggleClass('newclass');
    });
 });
</script>

How to execute myfunc() in 5000ms after toggleClass was executed? Tried several ways but with no luck.

Thank you.

I have

<script>
function myfunc(){
alert("show this alert in 5000ms after toggleClass executed")
//some code goes here
}

$(document).ready(function(){
    $('.mybtn').on('click',function(){
        $('#mydiv').toggleClass('newclass');
    });
 });
</script>

How to execute myfunc() in 5000ms after toggleClass was executed? Tried several ways but with no luck.

Thank you.

Share Improve this question asked Dec 23, 2013 at 9:22 HaradzieniecHaradzieniec 9,34833 gold badges122 silver badges227 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

use setTimeout()

function myfunc() {
    alert("show this alert in 5000ms after toggleClass executed")
    //some code goes here
}

$(document).ready(function () {
    $('.mybtn').on('click', function () {
        $('#mydiv').toggleClass('newclass');
        setTimeout(myfunc, 5000)
    });
});

Try this...

function myfunc(){
alert("show this alert in 5000ms after toggleClass executed");
//some code goes here
}

$(document).ready(function(){
    $('.mybtn').on('click',function(){
        $('#mydiv').toggleClass('newclass').delay(5000).queue(myfunc);        
    });
});

JSFIDDLE DEMO

Use settimeout function

function myfunc() {
    alert("show this alert in 5000ms after toggleClass executed")
    //some code goes here
}

$(document).ready(function () {
    $('.mybtn').on('click', function () {
        $('#mydiv').toggleClass('newclass');
        setTimeout(myfunc, 5000)
    });
});

You can have a callback function like this

$('#mydiv').toggleClass('newclass', 5000).promise().done(function(){alert("done")});

Here is a working demo

I would do the $("#mydiv").toggleClass('newclass') in a separate event.

For instance <button class="mybtn" onmousedown="$('#mydiv').toggleClass('newclass')" onclick="myfunc();">Fast Toggle</button>

If you toggle onmousedown the page will render with the toggle before the click event fires.

本文标签: javascriptjQuery execute a function AFTER toggleClass was executedStack Overflow