Why is my setTimeout function in JavaScript not working correctly?

I have a code snippet that is intended to display a series of numbers to users. Ideally, it should show:

1
2
3
4

However, the current implementation only displays:

1
4

Here is the code I am using:

    <script>
    function myFunction() {
    setTimeout(function() {
      document.getElementById('p').innerHTML = "1";
    }, 2000);

    setTimeout(function() {
      document.getElementById('p').innerHTML = "2";
    }, 4000);

    setTimeout(function() {
      document.getElementById('p').innerHTML = "3";
    }, 4000);

    setTimeout(function() {
      document.getElementById('p').innerHTML = "4";
    }, 4000);
    };
    </script>


<p id="p"></p>

<input onclick="myFunction()" type="submit" />

Can someone help me understand why this issue is occurring?

Thank you in advance.

Answer №1

due to

setTimeout(function() {
  document.getElementById('p').innerHTML = "2";
}, 4000);

setTimeout(function() {
  document.getElementById('p').innerHTML = "3";
}, 4000);

setTimeout(function() {
  document.getElementById('p').innerHTML = "4";
}, 4000);
};

making changes to the same element results in only displaying the output of the final operation: 4


The setTimeout() function schedules a function or expression to run after a specified time interval. in this scenario, all commands execute simultaneously due to the identical timing.

introduce intervals between them for proper execution.

Answer №2

When using setTimeout, the waiting time is calculated from the moment the statement is executed, not from the completion of the previous setTimeout.

This means that all setTimeout statements with delays set to 2, 3, and 4 will begin their 4-second wait nearly simultaneously.

Answer №3

If you continuously update the same element very quickly and set varying setTimeout values such as 1000, 2000, 3000, 4000, you will witness the content transitioning from 1 to 2 to 3 to 4 with approximately a one-second interval between each change.

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

Having trouble locating the module '.outputserver ode_modulespiniadistpinia' in Nuxt3 and Pinia?

I recently integrated Pinia into my Nuxt3 project, and while everything works fine in development mode, I encountered an error when trying to access the application in production mode resulting in the website freezing. [h3] [unhandled] H3Error: Cannot find ...

Load a Javascript file from the local server

My website is encountering a problem when trying to load a script from a localhost server. The error message displayed is PROTOCOL ERROR: https://localhost:4200/script/test.js net::ERR_SSL_PROTOCOL_ERROR Here is the code snippet causing the issue: <!DO ...

Clicking on a different texture/image allows for the texture to change in Three.js

I am working on creating a 360 image view using Threejs. I have a total of 4 images, with one linked to Threejs and the other 3 displayed as thumbnails at the bottom of the page. When a thumbnail is clicked, the 360 image view should change accordingly. Y ...

Instructions for removing the status bar from the configuration file

Struggling to remove the status bar that's covering my header in my Phonegap-wrapped HTML5 mobile app. I've tried adding preferences to the config.xml file, but still no luck. Here's what I added: <preference name="fullscreen" value="tr ...

Issue with content overlapping when hamburger icon is tapped on mobile device

When the hamburger menu is pressed on smaller screens, I want my navbar to cover the entire screen. To achieve this, I included the .push class in my code (see the jQuery and CSS) to trigger when the .navbar-toggle-icon is pushed. However, after implemen ...

Pattern for ensuring testability in JavaScript

I have come across two different JavaScript testable patterns, but I am struggling to understand the distinctions between them and which one would be more suitable for my needs. Pattern 1: function MyClass () { this.propertyA = null; this.methodA ...

Angular's watch feature fails to trigger when the value is modified

My setup includes two sliders, one for brightness and the other for contrast. They are linked to a "brightness" model and a "contrast" model. These sliders are located within a tab interface, and I noticed that every time the tab was changed, the values we ...

Displaying a section of an element

In my variable fieldErrors, I have the text enclosed in quotation marks saved like this: Object { url_title="This URL title is being ... titles must be unique."} Is there a way to display only the text within the quotes? (This URL title is being ... tit ...

Steps to emphasize HTML content and store it in the database for later use

I am currently working on a project that involves highlighting selected text within an HTML page that is loaded using PHP + XSL transformation. While I have come across solutions for highlighting the current selected text, I require the functionality to sa ...

Using ES6 to create a callback function that stores values in a Map

I've been trying to find an answer to this question by searching extensively, but haven't had any luck. Currently, I am developing a React app and faced with the task of storing the state, which happens to be a map, in a local variable. Here is ...

Show picture in web browser without the file extension

Is there a way to display an image in the browser without the file extension, similar to how Google and Unsplash do it? For example: Or like this: ...

Leveraging $http or $timeout in conjunction with $stateProvider in AngularJS

I am seeking guidance on loading a template for a specific state in Angular using $http after coming across this question on Stack Overflow: Is it possible to load a template via AJAX request for UI-Router in Angular? The documentation for ui.router demon ...

Display the element only if the value of the data attribute in the select option matches

Utilized HTML along with VueJS to display a div when the value is "two", and it is functioning correctly. Now, the objective is to use the data attribute - data-is-valid, to show div elements. If data-is-valid is set to true, then the div element should b ...

Django failing to append a string to models

Recently, I encountered an issue while restarting my project from scratch. Upon manual addition of a value to my Django model, everything works fine. However, when attempting to pass a value from a user-entered variable, only a blank string gets passed. T ...

Get the HTML code of a webpage that incorporates JavaScript into its design

Currently, I am attempting to retrieve the HTML code of a webpage using wget --load-cookies=cookies.txt However, I seem to only be able to access the main page's HTML without the content generated after JavaScript execution. I am hoping to retrieve ...

Using jQuery for client-side validation when the user clicks a button in an ASP.NET application

My goal is to implement field validation on button click using Jquery, but I'm facing an issue where it seems like the code behind event and the jQuery event are executing simultaneously. (UPDATED) <asp:Button ID="btnsave" runat="server" ClientI ...

Is there a method to develop an application utilizing the local web page as the interface?

Just a few days ago, I came up with the idea to create my own user-friendly "interface" for organizing and accessing some of my personal files. Having all related data, images, and links easily accessible with just a few clicks sounded very convenient to m ...

The feature of window.open and pop-up blocker integrated into the $.ajax().done() function is

When my jQuery ajax call is completed, I need to open a URL in a new tab. Here's the function I created for this purpose: var openNewTab = function() { window.open('/UrlToOpen', '_blank'); win.focus(); } If I directly cal ...

Vanish Dropdown upon clicking Using JavaScript

Hey, I'm new to web development and I'm currently working on creating a web app for iPhone. Everything is going smoothly except for one issue - my dropdown menu works perfectly on desktop Chrome, but on the iPhone's Safari browser, I can&ap ...

Is the behavior of a function with synchronous AJAX (XMLHttpRequest) call in JavaScript (Vanilla, without jQuery) the same as asynchronous?

I'm facing an issue with a file named tst.html and its content: part two (purely for demonstration, no extra markup) The challenge arises when I try to load this file using synchronous AJAX (XMLHttpRequest): function someFunc() { var str = &ap ...