Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are there any downsides calling a function in javascript every ~100ms?

So I started exercising javascript and html for a couple of days now and I wanted to know if there are any downsides (especially looking at performance reasons) if I call a function every 80ms (with the setInterval() function).

I made a calculator and I have a function which "synchronizes" my input value with a label, which will also show me the result.

<label id="rechnung" for="eingabe"> </label>
<input id="eingabe" name="Eingabe" class="inputField" oninput="filterInput()">

 window.onload = setInterval(syncEingabeRechnung,80);
 function syncEingabeRechnung(){
      document.getElementById('rechnung').textContent = document.getElementById('eingabe').value;
 }

The reason with the repetitive calling is for cases when someone highlights characters and deletes them. This way the input field and the label wouldnt have identical values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

P.S.: If there is a better way to achieve my intend, then I would like to hear your ideas!

>Solution :

No, the performance cost would be very low (if your function just does what it says), besides the fact that that’s a very bad approach. You would think that the browser knows when the user is typing, and maybe the browser thinks that it’s a good idea to let the JS know as well. The browser has pre-provided built-in things for you to use that are much better, where you listen for any changes in input and update the label accordingly.

Something like this:

const input = document.getElementById("inp"),
  l = document.getElementById("l");

// we can simply wait for the input event
input.addEventListener("input", () => {
  l.innerText = input.value; // update the label accordingly
});
<label id="l" for="inp"></label>
<input placeholder="Type something..." id="inp" />

However you change the input contents (typing, highlighting, deleting), the change will always register.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading