0

I have always a misunderstanding with javascript and how the call to a function work.

I have a range input, and send the value via api, the problem I'm having is that:

Sliding the range I send a lot of request, so I would like to wait the end of user input or sliding in my case and then send te request.

What happend if I call a lot of time a function in js?? Any time the function restart or a new instance of that function will be started??

Cause at the actual state of art if I put the range in the end it will generate from 5 to 10 request with the same value.

This is the html code:

<input type="range" min="0" max="1023" value="0" class="py-2" id="swtchvalue0" oninput="setSWstate(0)">

This is the function:

    function setSWstate(sw){
    const value = document.getElementById(valuePrefix + sw).value;
    let http = new XMLHttpRequest();
    let params = 'sw=' + sw +'&value=' + value;
    const errdiv = document.getElementById(errorPrefix + sw);
    // setting value, if not ok will overwrited after from getswitchstate and hide error div
    document.getElementById(valuePrefix + sw).value = value;
    errdiv.classList.add("hidden");

    http.open('POST', "/setsw?"+ params, true);
    //Send the proper header information along with the request
    http.setRequestHeader('Content-type', 'application/json');

    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            if(http.responseText === "ok"){
            } else {
                document.getElementById(errorPrefix + sw).innerHTML = http.responseText;
                errdiv.classList.remove("hidden");
            }
        }
    }
    http.send(params);
}

How can I wait something like 300ms to filter the end of the sliding??

Stefano Martini
  • 306
  • 1
  • 10

0 Answers0