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

the term 'this' does not pertain to the user object within the mongoose model

Here is a snippet of my code that saves a user object to a database using Express: api.post('/signup', function (req, res) { var user = new User(); user.name = req.body.name; user.email = req.body.email; user.setPassword(req.body ...

Having trouble with overriding an @media query for material-ui react components?

I've been trying to modify a @media CSS rule on a Material UI component, similar to the discussions on How to over-ride an @media css for a material-ui react component and Override components like MuiTab that use media queries. However, I have not bee ...

Can the mDNS string received through webRTC be decoded to retrieve a user's IP address?

After doing some thorough research, I came across this insightful response from a different Stack Overflow question. The problem at hand involves retrieving an mDNS string, which looks like this: abcd1234-1e1e-1e1e-1e1e-abcd1a2bc3de.local I have a genuin ...

Warning: The current version of graceful-fs (3) is deprecated in npm

I encountered an issue while running npm install. I attempted to run the following command before updating: $npm install npm, and also updated graceful-fs. $ npm install -g graceful-fs <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

I'm curious about the location where label_color keys are stored within apache-superset

Version: I have installed a Docker instance of Superset from this source The documentation mentions that colors can be customized based on labels, as explained here. To achieve this, it is necessary to provide a mapping of labels to colors in the JSON ...

"Adding an active class to a link based on the current page and locale: A step-by-step

Looking to add an active class to the subheader menu on the active page, but facing issues when changing the locale in the link. While it works for links like my-site/my-page, it doesn't work for links like my-site/fr/my-page. Utilizing Storyblok head ...

Is it possible to include multiple API routes within a single file in NextJS's Pages directory?

Currently learning NextJS and delving into the API. Within the api folder, there is a default hello.js file containing an export default function that outputs a JSON response. If I decide to include another route, do I need to create a new file for it or ...

Why am I unable to utilize methods in Vue.js?

Hey everyone, I'm currently working on a website that includes a home page and a specific 'Brazil' component. To switch between the two, I am using vue router. Within the Brazil component, there is a calculator feature that should take a gra ...

Randomizer File Name Maker

I was questioning the behavior of Multer Filename. If Multer stores files with random filenames, is there a possibility of two files having the same name in Multer? In other words, if I am storing files from a large number of users, could the filenames e ...

Employing res.sendStatus(200) in conjunction with JQuery AJAX

I've implemented a form that triggers an AJAX call to my backend, utilizing Node and Express. The onsubmit function is responsible for this interaction. Once the submission is successful, I use res.sendStatus(200) to inform the client. This results i ...

finding the initial element within an object using lodash in javascript

Recently, I came across some data in the form of an array of objects. For instance, let me share a sample dataset with you: "data": [ { "name": "name", "mockupImages": "http://test.com/image1.png,http://test.com/image2.png" }] ========================== ...

What could be the reason behind my inability to successfully install and utilize Bootstrap Multiselect?

Hey everyone, I'm facing an issue while trying to implement Bootstrap Multiselect through NPM installation. I encountered an error stating $(...).multiSelect is not a function. Despite referring to the documentation, I am unable to utilize the library ...

Why is Ajax having trouble showing PHP's JSON data? What could be causing the issue with the JSON format?

After thoroughly reviewing all related questions on the topic, I still haven't been able to find a solution. When I attempt to integrate JSON into my PHP and AJAX code for passing data, that's when the trouble begins. Here is the AJAX portion o ...

Having trouble retrieving cookie in route.ts with NextJS

Recently, I encountered an issue while using the NextJS App Router. When attempting to retrieve the token from cookies in my api route, it seems to return nothing. /app/api/profile/route.ts import { NextResponse } from "next/server"; import { co ...

A guide on getting the `Message` return from `CommandInteraction.reply()` in the discord API

In my TypeScript code snippet, I am generating an embed in response to user interaction and sending it. Here is the code: const embed = await this.generateEmbed(...); await interaction.reply({embeds: [embed]}); const sentMessage: Message = <Message<b ...

When the browser is refreshed, jQuery will automatically scroll the window down

I created a div that matches the height and width of the window to simulate a "home screen." When scrolling down to view the content, everything works fine. However, after refreshing the browser, it automatically scrolls back to where you were before. I wa ...

Attempting to modify the key values within an object, however, it is mistakenly doubling the values instead

I'm encountering an issue when trying to update key values within an object. It seems to be adding duplicate values or combining all values together instead of assigning each name a specific language slug. I can't figure out where I'm going ...

JSONP request resulted in a syntax error

I'm having trouble retrieving data from a JSONP source, as it keeps throwing a Syntax error when the function is called. I am quite new to this subject and find it hard to understand why this error occurs. It seems like my understanding of JSONP reque ...

Swapping out DIVs with jQuery

Currently, I am working on a project for a client where I need to create a sortable biography section using jQuery. Initially, I had a setup with just two bios (first person and third person) which was functioning perfectly: $("a#first").click(function() ...

JQuery shake effect for dynamic text animation

Hey there! I need some help figuring out how to stop this shaking effect after it shakes three times. Do you think using set or clearInterval could do the trick? Any advice would be much appreciated! function interval() { $('#shake') ...