Haradzieniec Haradzieniec - 4 months ago 27
Javascript Question

jQuery: execute a function AFTER toggleClass was executed

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.

Answer

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)
    });
});