'Run function only once for particular element [duplicate]

I am building a simple todo app and I am new in JavaScript and I am stuck in a problem.

I am trying to run function only once for a particular element ID. like,

There are 5 divs with IDs 1,2,3,4,5. so I am accessing them by className and then their ID.

Then I am storing their id in a variable and storing it to prevent the function from running with the previous id.

page.html

function myFunction() {

    // Used for getting last element of all the classes
    var element = Array.from(document.querySelectorAll(".fields")).pop();

    var previousId = element.id;

    var executed = false
    if (previousId === element.id) {
         if (!executed) {
            executed = true;
            console.log("Run only once");
            console.log(previousId);
        }
    }
}
<input type="text" id="1" oninput="myFunction(id)" class="fields">

<input type="text" id="2" class="fields">

What I am trying to do ?

I am trying to run the function only once for the current input field user is typing in.

I tried removing if (previousId === element.id) { and running only if(!executed){ but it also didn't worked.

But Whenever I type in input field then it executing every time I press the key.

I have tried many times but it is still not working. Any help would be much Appreciated. Thank You in Advance.



Solution 1:[1]

You can save an array of already runned id and chek it

let alreadyRunned = []

function myFunction(id) {
  if (alreadyRunned.includes(id)) {
    return;
  }
  alreadyRunned = [...alreadyRunned, id]
  console.log("Run only once");
  console.log(id);
}
<input type="text" id="1" oninput="myFunction(1)" class="fields">

<input type="text" id="2" class="fields" oninput="myFunction(2)">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 R4ncid