July
July

Reputation: 77

What is the best way to stop function from running multiple times in Js

var emps;

function GetEmps(){
    const Http = new XMLHttpRequest();
    const url='http://127.0.0.1:3001/GetEmployeeList';
    Http.open("GET", url);
    Http.send();
    Http.onreadystatechange = (e) => {
        e.preventDefault();
        if(Http.responseText.length>0)
        {
            emps=JSON.parse(Http.responseText);
            
            for(let i=0;i<emps.length;i++)
            { 
                CreateElementsInPage(i);    
            }
                   
        }
    }

}
function CreateElementsInPage(id) {
    
    console.log(id);
    var btn = document.createElement("BUTTON");
    btn.innerHTML = emps[id].name;
    document.body.appendChild(btn);

    var newLine=document.createElement("br");
    document.body.appendChild(newLine);
}


GetEmps();

i am trying to create buttons dynamically. for every item in emps array, I want a button to appear in the DOM, but the "CreateElementsInPage" functions get called 4 times instead of 2 (suppose I have 2 items in emps) and I get 4 buttons enter image description here

Upvotes: 1

Views: 197

Answers (2)

Mzndako
Mzndako

Reputation: 82

onreadystatechange event function is triggered/called whenever the state of the connection is changed (readyState).

So you need to make sure that you create your button only when the connection is successful (done).

function GetEmps(){
    const Http = new XMLHttpRequest();
    const url='http://127.0.0.1:3001/GetEmployeeList';
    Http.open("GET", url);
    Http.send();
    Http.onreadystatechange = (e) => {
        // Make sure that the request is done before calling your button creation method
        if (Http.readyState === XMLHttpRequest.DONE) {
           if(Http.responseText.length>0)
           {
               emps=JSON.parse(Http.responseText);

               for(let i=0;i<emps.length;i++)
               { 
                   CreateElementsInPage(i);    
               }

           }
       }
    }

}

Upvotes: 1

Pavel Lint
Pavel Lint

Reputation: 3527

You should check request state inside your callback:

Http.onreadystatechange = (e) => {
  if(Http.readyState === XMLHttpRequest.DONE ) {
      // Request is complete, do your logic
  }
}

Upvotes: 3

Related Questions