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" 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.
P.S.: If there is a better way to achieve my intend, then I would like to hear your ideas!
CodePudding user response:
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.