The full execution of Jquery show() does not pause until it finishes

Here is the sequence I want to achieve:

  1. Show a div element with the CSS class yellow
  2. Execute a function for about 5 seconds
  3. Remove the yellow class and add the green CSS class "state Ok"

However, when running my code, the div container does not appear until after the function has finished. What am I missing?

function sleepFor(sleepDuration) {
    var now = new Date().getTime();
    while (new Date().getTime() < now + sleepDuration) { /* do nothing */ }
}



function DoIt() {
    $('#divState').show(100, function() {});
    sleepFor(1000);    
    $("#divState").removeClass("Yellow").addClass("Green");
}
div {
    display: none;
}


div.Green {
    border: 1px solid black;
    background-color: #93EEAA;
}

div.Yellow {
    border: 1px solid black;
    background-color: #FFEE99;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="button" onclick="DoIt()" value="run" />
<div class="Yellow" id="divState">Some Text</div>

Answer №1

If your goal is to display an element, you can achieve this using jquery.show. You can also add a delay if needed by utilizing jquery.delay, followed by queuing up the removal of the "Yellow" class and addition of the "Green" class using jquery.queue.

function DoIt() {
    $('#divState').show(100).delay(1000).queue(function(){
          $(this).removeClass("Yellow").addClass("Green");
          $.dequeue(this)
      });
   
}
div {
    display: none;    
}


div.Green {
    border: 1px solid black;
    background-color: #93EEAA;
}

div.Yellow {
    border: 1px solid black;
    background-color: #FFEE99;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="button" onclick="DoIt()" value="run" />
<div class="Yellow" id="divState">Some Text</div>

Answer №2

Have you ever wondered why some developers use an empty while loop in their JavaScript code? In reality, there is a native method available that allows you to wait for a specific amount of time without the need for such loops. If you had simply searched online, you would have discovered this handy function right away.

setTimeout(function() {
    $("#divState").removeClass("Yellow").addClass("Green");
},5000);

By using the setTimeout method, you can effectively pause execution for 5000 milliseconds before triggering the specified callback function. This can be easily incorporated into your button click event like so (assuming your button has the id myButton):

$("#myButton").click(function(){
    setTimeout(function() {
        $("#divState").removeClass("Yellow").addClass("Green");
    },5000);
});

This approach is far superior to relying on the "onclick" attribute within your HTML elements, as it promotes unobtrusive coding practices and helps maintain cleaner code overall.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to choose an Animatedmodal that can showcase various demos while using just one ID?

I am currently customizing my website and utilizing the AnimatedModal.js framework. I have successfully displayed content in one modal, but encountered difficulty when attempting to create multiple modals as they all share the same ID. My question is, how ...

Can the month dropdown in react-datepicker be modified to display numbers instead of names?

Here is the code I have: <DatePicker selected={value?.toDate()} onChange={(date) => this.handleMonthChange(date)} inline showMonthYearPicker dateFormat={this.props.formatString} /> I am seeking to modify it so that instead of d ...

Ways to deactivate remaining buttons until a function call finishes after selecting one in a react render() function?

In order to prevent the overlap of results when multiple buttons are clicked simultaneously, I need to disable all toggle buttons until one function call is complete, including the reset button. Additionally, I'm looking for a way to display my functi ...

Chrome and Internet Explorer are not prompting to save passwords after the input type has been altered by a script

I've encountered an issue with a form that includes: <input type="password" id="password" /> I want to display some readable text temporarily, so I used the following code: $('#password').prop('type', 'text'); ...

Exploring Django's HTML QuerySet

Is there a way to verify if a student exists in the database class table, given that the student is assigned as a foreign key in the table? I am looking to achieve this without opening another loop. index.html: <ul> {% for student in studentList %} ...

Checkboxes within Angular's reactive forms are a powerful tool for creating dynamic user

Currently, I am working on a contact form that includes checkboxes for users to select multiple options, with the requirement of selecting at least one box. My challenge lies in figuring out how to pass all the selected checkboxes' data to an API usin ...

Preventing state changes from affecting the rendering of a Material-UI table in a ReactJS application

Inside my app.js, the following code snippet defines a state: const [open,setOpen] = useState(false) This state is used to control whether a material-ui Alert should be displayed on screen for 3 seconds using this code: useEffect(()=>{ setTimeout( ...

What could be causing my code to lag by 2 ticks instead of just 1?

Apologies for any spacing issues. Player = { move: function(cycle, opponent) { switch(cycle.current_direction) { case 'up': cycle.y -= cycle.height; break; case 'down': cycle.y += cycle.hei ...

Loading images in advance using jCarousel

I need help with preloading images on a jCarousel that loads a JSON feed and generates necessary HTML. Can anyone suggest a way to accomplish this task efficiently? $(".banner ul").jcarousel({ itemLoadCallback:loadTopBanner, auto: 6, wrap: ...

What is the meaning of a "hook" in the world of HTML?

During a recent interview, a developer asked me about the "hooks" Angular uses with HTML. I admitted that I was not familiar with the term "hook," despite my extensive experience in web development over the past two decades. While I have some ideas of what ...

Utilize the Image URL for training your Tensorflow.js application

I'm currently exploring how to use images sourced from the internet for training my neural network. I am utilizing an Image() object to generate the images and pass them to tensorflow. Despite my understanding that Image() should return a HTMLImageEle ...

Parcel js is encountering difficulties running the same project on Ubuntu

I have encountered an issue with my JavaScript project when trying to run it on Ubuntu using parcel 2 bundler. The code works perfectly fine on Windows, but in Ubuntu, I am facing errors. Despite trying various solutions like cleaning the cache and reinsta ...

The body parser is designed to efficiently parse and handle both gzip and json formatted HTTP POST request bodies

I've set up an API endpoint to manage http POST requests from a client. At the moment, I'm using Express framework and bodyParser to handle request bodies. What I need help with is configuring body-parser to effectively handle cases where request ...

What is the best way to redirect a user to a different URL in Express while also sending additional data along with the request

[NODE, express] Developing a Facebook application where user grants access and is redirected to my site with a unique code at abc.com/heyBuddy/fb/callback?code="adasdasdasda". Once the code is received in route router.get('/heyBuddy/fb/callback', ...

Converting and storing Canvas data as a blob, and then saving the blob as

There is a clickable icon on the page that triggers an action when clicked. Currently, the icon is set as an anchor tag. However, I want to change it to a div like all the other icons in my UI. But for some reason, the following code isn't working. W ...

Implementing auto-complete functionality using two keys in Material UI and React

My goal is to enable autocomplete for input when searching with values like title and year. Strangely, the autocomplete feature only works when I search with title. Searching with year does not yield any options. Sample code export default function ComboB ...

The vertical scroll function in JQueryMobile Autocomplete seems to be malfunctioning on Android devices

Incorporating jQuery Autocomplete into my jQueryMobile application has been a success. However, I am facing an issue where I am attempting to display a vertical scrollbar in order to navigate through the list of retrieved items. Strangely, the scrollbar ap ...

Exploring the Depackaging of ES6 Nested Objects

How can I implement ES6 with Destructuring to give users options? I'm having trouble dealing with nested objects and preventing the defaults from being overwritten by partial objects. Check out this simple example on MDN: function drawES6Chart({si ...

Utilize the composite primary key of an Entity within Typeorm for efficient data retrieval

I am working with the following database entities: @Entity() class Team { @PrimaryGeneratedColumn() id: string @PrimaryColumn() teamName: string @OneToMany(() => Player, player => player.team) players: Player[] } @Entity() class Player ...

Consistent Row Heights for Dynamic Width Elements

I've relied on Chris Coyier's Equal Height Blocks in Rows jQuery script for various projects, and it has consistently delivered great results. However, this time I am facing a new challenge as I work on a responsive website with a fluid width ma ...