-3

Given the next code:

formInput = Array.from(document.getElementsByClassName('form-input'));
    formInput.forEach(element => {
        setInterval(() =>{
            element.required = true;
        }, 1000)
    });

Once the element is required. Will the setInterval() keep running and setting it to required every second and worsen the performance? Or as it's already required = true it will stop running?

Space guy
  • 375
  • 5
  • 14
  • 1
    The interval will keep running and perform the useless operation every second (because, as you said, `required` will already be `true`). It will probably be undetectable performance wise, but you probably want to use `setTimeout` which does it only once. – Jeremy Thille Sep 07 '21 at 14:44
  • 2
    Sounds like a [x/y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why would you want to set the required to true each second? – 0stone0 Sep 07 '21 at 14:44
  • 1
    @0stone0 I don't think OP wants to set `true` every second. They realise it's useless. My guess is, since they don't know how to set it only once (with setTimeout), they ask if setting it every second will impact performance. – Jeremy Thille Sep 07 '21 at 14:47
  • Why do you need to do this in a timeout at all? Just make them required directly. – Barmar Sep 07 '21 at 14:49
  • 1
    @Spaceguy The user can remove this code, so if they really want to get around the validation they can. Why aren't you validating on the back end? Client-side validation is just a convenience, it should never be critical. – Barmar Sep 07 '21 at 14:52
  • The user will always be able to alter the form locally. You **should** do a backend check on the data. – 0stone0 Sep 07 '21 at 14:52
  • 1
    Do you know about tools like Postman? It's a child's play to send a form to your backend without even visiting your frontend. Anybody can send anything to your backend. It's required to validate the form in the backend. – jabaa Sep 07 '21 at 15:35

1 Answers1

-6

setInterval() function rarely affect performance. I don't think you need to worry about such trifling code segment. I recommend you visit here

WOW
  • 1
  • Something like `setInterval(() => document.querySelectorAll('*'), 1);` will have significant impact on the performance of a site. Please take a look at [answer] regarding link-only questions. – 0stone0 Sep 07 '21 at 14:52
  • Please add further details to expand on your answer, such as working code or documentation citations. – Community Sep 07 '21 at 15:56