The setTimeout function executes immediately without any delay

In my code, an html button triggers a jQuery function (let's call it funcOne) which then calls another function (funcTwo) recursively to modify CSS in the DOM. The funcTwo function involves setTimeout() calls to create a blinking effect by delaying the CSS changes.

Here is an example of how funcOne looks:

function funcOne(stringOfNumbers){

    //This function executes other tasks that do not interfere with funcTwo
    someUnrelatedFunction(); 

    funcTwo(time);

    return;
}

An example of funcTwo would look like this:

function funcTwo(time){

    if(time == ""){return true;}

    var delay = time.charAt(0);
    var numDelay = parseInt(delay);

    setTimeout(function(){
        $("#container").css("background-color", "white");
        console.log("Changed to white");
    }, 1000); //Arbitrary delay

    setTimeout(function(){
        $("#container").css("background-color", "black");
        console.log("Changed to black");
    }, numDelay); //Variable delay

    time = time.substr(1);

    return funcTwo(time);

}

Despite seeing both messages in the console, indicating that the script is running without any stack overflow errors, I'm encountering a problem. Both delays, the arbitrary and variable, are not functioning as intended - the #container immediately turns black without waiting for the delays.

I am seeking assistance to identify what I might be doing incorrectly. Any help or guidance would be highly appreciated.

Answer №1

One issue that stands out is the maximum delay allowed before the color changes to black is 9 milliseconds. This is because the second variable delay is assigned the value of the first character of the time variable, which can only go up to 9. If you want the background color to change to white first, consider moving the second setTimeout() inside the first setTimeout(). This way, it will only be executed after the background turns white. Remember that setTimeout() does not immediately run the function; it prepares it for execution. In your code, this allows any code following the setTimeout() call to be executed before the function itself is actually triggered.

Answer №2

The setTimeout() function in JavaScript is used to schedule a function to run after a specified amount of time. It takes two parameters - the first one being the callback function to be executed and the second one being the time interval in milliseconds. In your case, you have set it to 1000ms, which is equal to 1 second. This means that the function will exactly run after 1 second.

setTimeout(function(){
    alert("Changed to white");
}, 1000); 

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

Enhance your app with the seamless navigation experience using Ionic 2

As a beginner in Angular2, Ionic2, NodeJS ... I am experimenting with writing some code to learn. In my journey, I attempted to create a screen with 3 tabs and a menuToggle. When the application is launched, clicking the menuToggle button on the first tab ...

Guide to embedding a qr code within a pdf document

I've been working on creating a PDF file generation feature where users can download the PDF with a QR code embedded in it. While I've successfully implemented the PDF generation part, I'm facing an issue with adding the QR code to the file. ...

Tips for extracting a value from a mongodb aggregate operation

I am attempting to retrieve a value from a MongoDB aggregate in order to display it on an EJS page using the totalAmount variable. The result I am currently receiving is [{"totalAmount":42}] and my goal is to extract only the number, in this case, 42. My ...

Chrome browser exhibits a phenomenon where the Bootstrap modal will erroneously print the same page multiple times based on the

When I open a modal, there's a print button inside it. I've researched solutions provided here and here to enable printing of Bootstrap modals, but I'm encountering a Chrome-specific bug. The issue doesn't occur in Safari, Firefox, or E ...

Utilizing Loops in a React Component's Function

(React web app development) I am currently working on a project where I need to check the stock status of products using their IDs in a JSON data loop. However, I am facing an issue with the condition checking for the ID match, as it always seems to return ...

Ways to access the HTML content of a component in vue.js

I have a unique html template displayed below CustomTemplate.vue <template> <div class="content custom-page"> <md-card class="page-display"> <md-card-header class="page-header"> <md-card- ...

Tips for incorporating jQuery UI into Angular 6

No matter how many methods I have tried from StackOverflow, I cannot seem to get jquery-ui to work in my angular 6 component. Here's what I've attempted: I went ahead and ran npm install jquery jquery-ui to install both jquery and jquery-ui. ...

How about trying out the magic of Bootstrap columns?

My issue pertains to bootstrap columns. Whenever I zoom in on the browser, the columns start overlapping and the text from col-md-7 ends up over the image. Does anyone know of a solution to this problem? <div class="row"> <div class="col-md-5 ...

Unable to retrieve JSON element in ReactJS

Here is the code snippet that I am currently working with: const [questions, setQuestions] = useState([]) useEffect(() => { let idVar = localStorage.getItem('idVarianta'); idVar = JSON.parse(idVar) axios({ ...

Authenticating the Gmail API using a specified user ID

Is there a way to manually input email and password for authentication in the Gmail API without using the default Google popup? I need users to enter their login credentials directly, but I can't figure out how to do it. The code I am currently using ...

Order of flexbox items when placed within separate divs?

Looking to rearrange the order of items using flexbox, but hitting a roadblock because one of the items I want to reorder is in a different div and not a direct child of the same parent as the other items. <div class="wrapper"> <div class="some ...

"Caution: Please be aware of potential header errors when accessing a static map through AJAX

When attempting to retrieve a static map image using AJAX to check for errors, I encountered the following message: Refused to get unsafe header "x-staticmap-api-warning" (seen in Chrome) I am not very familiar with headers, but it appears that they nee ...

Vue Array Proxy Class Fails to Trigger Reactivity

My custom Array extension has a feature where it intercepts changes made to its properties using Proxy, which is returned from the constructor. However, when used in a Vue component, it encounters issues. For example, when a filter is added, the display do ...

Div remains fixed while scrolling until the footer is reached

Hi there, I could really use some assistance with a jQuery issue I'm facing. I've been watching tutorials in an attempt to find a solution, but being new to jQuery, I'm struggling. My goal is to scroll a fixed div down the page, however when ...

What are some methods for altering ReadOnly values?

I am encountering an issue with the value fetchOptions: Readonly<HttpFetchOptionsWithPath> and my attempt to overwrite one of its properties. Here is the method I have tried: ((fetchOptions as Writable<HttpFetchOptionsWithPath>).headers as Wr ...

Customize the appearance and text in the navigation bar

Currently, I am in the process of creating my own personal website template. However, I have encountered an issue with styling the image and text within the navbar. I am looking to adjust the aspect ratio of the image in order to center it within the n ...

Exploring ways to incorporate or eliminate animations on mobile devices using html/css

Is it possible to control animations on different devices using media queries? For example, can you show an animation only on mobile devices while hiding it on desktop or laptop? Conversely, is there a way to add an animation specifically for mobile device ...

method for sorting labels in Select element in ReactJS

Hey there, I'm facing an issue with the code snippet available here. I would really appreciate it if you could assist me in resolving this problem. This is the code: import React from "react"; import { Select } from "antd" ...

Using hooks to call a function in a different function is not allowed

The log out feature allows a user to sign out by initiating an API request and removing the user's data from LocalStorage and the Redux store. To achieve this, the function utilizes two hooks: useDispatch and useFetch (a custom hook). import {useDispa ...

Tips for calculating the total of an array's values

I am seeking a straightforward explanation on how to achieve the following task. I have an array of objects: const data = [ { "_id": "63613c9d1298c1c70e4be684", "NameFood": "Coca", "c ...