Does the setTimeout function stop execution?

I stumbled upon a problem with setTimeout.

$current.removeClass(class2);
setTimeout(function(){$current.css('display', 'none')},1000);
if(!$current.is('#' + id)){
    $('#' + id).css('display','block');
    setTimeout(function(){$('#' + id).addClass(class2)}, 1000);
    $current = $('#' + id);
}

      

I want the if statement to execute AFTER I add the css "display: none". How can I achieve this? I thought setTimeout would stop executing the code and then continue executing the function.

+3


source to share


2 answers


You put this code inside a function during the timeout (it is also important to use a spacing between codes ...):



$current.removeClass(class2);
setTimeout(function() {
    $current.css('display', 'none')

    if( !$current.is('#' + id) ) {
        $('#' + id).css('display','block');
        setTimeout(function() {
            $('#' + id).addClass(class2)
        }, 1000);
        $current = $('#' + id);
    }
},1000); 

      

+1


source


setTimeout

will run the function after n milliseconds, but the rest of the script will continue to run.

If you want the rest of the code not to run until after display:none

you need to move it into a function:



$current.removeClass(class2);
setTimeout(function(){
  $current.css('display', 'none');

  if(!$current.is('#' + id)){
    $('#' + id).css('display','block');
    setTimeout(function(){
        $('#' + id).addClass(class2);
    }, 1000);
    $current = $('#' + id);
  }
},1000);

      

+1


source







All Articles