Explain the inner workings of the setTimeout() function in JavaScript

My goal is to create a line in my code by placing points according to the line equation and adding a 100 millisecond delay before each point is displayed. However, when I try to run the code, it seems to wait for some time and then displays all the points at once without the desired delay.


function drawLine(x1, y1,x2,y2){
    var x, y, m;
    m=(y2-y1)/(x2-x1);

    for(x=x1;x<=x2;x++){
        y=(m*(x-x1)+y1)/6;
        setTimeout(drawPoint,100,x,y);
    }
}

function drawPoint(a,b){
    main=document.getElementById("main");     
    var children=main.childNodes;
    var child=document.createElement("div");

    child.className="anime";
    child.style.left=a+"px";
    child.style.top=300-b+"px";             

    main.appendChild(child);     
}  

If anyone has any suggestions or solutions, they would be greatly appreciated.

Answer №1

When using a for-loop, it's important to note that it is non-blocking. This means that all the setTimeout instances within the loop will execute once the specified duration has elapsed.

One way to ensure that every handler in a loop is invoked in multiples of 100 milliseconds is to maintain a counter and use it as the milliseconds argument in each setTimeout() call.

function drawLine(x1, y1, x2, y2) {
  var x, y, m;
  m = (y2 - y1) / (x2 - x1);
  var counter = 1;
  for (x = x1; x <= x2; x++) {
    y = (m * (x - x1) + y1) / 6;
    setTimeout(drawPoint, (100 * counter), x, y);
    ++counter;
  }
}

function drawPoint(a, b) {
  main = document.getElementById("main"); //parent div tag in which children div tags are to be appended
  var children = main.childNodes;
  var child = document.createElement("div");
  child.className = "anime";
  child.style.left = a + "px";
  child.style.top = 300 - b + "px"; //300 is some offset
  main.appendChild(child);
}

Answer №2

Consider utilizing the setInterval() method as an alternative to setTimeout

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

Incorporating Ruby on Rails: Sending a fresh POST request to API and instantly

I'm a beginner in the field of ruby on rails. Our website allows users to search and receive a list of results. Now, I want to incorporate sorting functionality for the results (by price, rating, etc). The API handles the sorting process, so all I ne ...

Creating an overflow effect for sliders using only CSS

Is it feasible to develop a slider that extends beyond its parent elements and the body? The concept involves having content within a section housed in a container. The slider would be part of this section, with slides overflowing past the parent element ...

Halt and anticipate a boolean reply from another function

Is there a way to create two functions in JavaScript, run one of them, then within that function, execute the other and pause until it receives a response (yes or no) before moving on to an if statement? The user's response should be manual. Here is ...

When any part of the page is clicked, the data on the Angular page will automatically

Clicking the mouse anywhere on the page, even in a blank spot, causes the data array to resort itself. I understand that clicking may trigger a view change if an impure pipe is set, but I have not used one. So I am puzzled because my development testing ...

Tips for choosing a visible element in Protractor while using AngularJS

I am working on a Single Page Application that contains multiple divs with the same class. My goal is to have protractor identify the visible div and then click on it. However, I keep encountering the error Failed: element not visible, which leads me to be ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

How can I adjust the size of my elements to be responsive in pixels

While browsing through Quora and Facebook feeds, I noticed the fixed size of user display pictures: width: 40px; height: 40px; Even when resizing the browser window for a responsive design, these pictures maintain their size at 40px x 40px. What other f ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

Leveraging jQuery within a method defined in an object using MyObject.prototype.method and the 'this' keyword

Recently, I've started exploring Object-oriented programming in JavaScript and have encountered a challenge. I'm trying to define an object like the example below, where I am using jQuery inside one of the methods. I'm curious about the best ...

Mastering the integration of this asmx webservice with jQuery/ajax

Hello, I need some assistance with a webservice that I have. The webservice URL is My goal is to display a list of products from this service (where ObtenerProductosPorId translates to GetProductsById) on an HTML page. I have been researching how to achi ...

Is it secure to store the access token within the NextAuth session?

Utilizing a custom API built with Node.js and Express.js, I have implemented nextAuth to authenticate users in my Next.js application. Upon a successful login, the date is stored in the nextAuth session and can be accessed using the useSession hook. To acc ...

Adding variables to a div using jquery

Is there a way to use jQuery to append variables to a div? Below are my codes, but I am looking to display div tags in the append. For example: .append("" + p + "") var image = item.image; var label = item.label; var price = item.price; ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

The export of 'alpha' is not available in the '@mui/system' module

Help! I am encountering an error related to the @mui/material library. I have already looked into the package.json file of mui/system and it seems that 'alpha' is exported in it. ./node_modules/@mui/material/styles/index.js Attempted import erro ...

What is the process for deleting an event in Vue?

My Vue instance currently includes the following code: async mounted () { document.addEventListener('paste', this.onPasteEvent) }, beforeDestroy () { document.removeEventListener('paste', this.onPasteEvent) }, methods: { onPasteEv ...

I'm facing an issue where I am only able to update the first record in the database using axios and Post

There seems to be a strange issue where only the first record in the database can be updated, even though all records can be retrieved without any problems. Here is the situation: https://i.sstatic.net/bK5aI.png To clarify further: Since names are unique, ...

Sorting a list with anchor tags alphabetically using Javascript/JQuery

Here is a list of services: <ul id="demoOne" class="demo"> <li><a href='http://site/Service.aspx?shId=1154'>Copy service for files from folder 12</a></li> <li><a href='http://site/Service.aspx? ...

Creating a list of identical elements with shared attribute values using nightwatch.js or JavaScript - a step-by-step guide

I have been using nightwatch.js for automating tests on a web application, and I am facing difficulties in creating a list of elements that share common values in their attributes. Below is an example: The first three spans with a common value for the att ...

I am facing an issue where my Tailwind classes are not functioning properly when passed through props, but they work seamlessly when I directly link the Tailwind CSS using

//Button.jsx import React from 'react'; const Button = (props) => { let color = props.color || 'blue'; return ( <button className={`px-4 py-2 font-bold text-black bg-${color}-500 rounded-full hover:bg-${color}-700 focus ...

When the Jqueryui dialog is closed, it effectively terminates the current JavaScript thread

Hello there, I'm currently facing an issue with closing my jQuery dialog box. The situation involves a comet connection that sends messages to my browser. My goal is to perform certain actions upon receiving a message, close the dialog, and then conti ...