Avoiding a javascript race condition

后端 未结 7 2256
醉话见心
醉话见心 2020-12-23 12:26

Here\'s the scenario:

My users are presented a grid, basically, a stripped down version of a spreadsheet. There are textboxes in each row in the grid. When they ch

7条回答
  •  心在旅途
    2020-12-23 12:42

    A semaphore or mutex is probably the best way to go, but instead of a busy loop, just use a setTimeout() to simulate a thread sleep. Like this:

    busy = false;
    
    function UserInputChanged(control) {
        busy = true;
        currentControl = control;
        // use setTimeout to simulate slow validation code (production code does not use setTimeout)
        setTimeout("ValidateAmount()", 100); 
    }
    
    function SaveForm() {
        if(busy) 
        {
           setTimeout("SaveForm()", 10);
           return;
        }
    
        // call web service to save value
        document.getElementById("SavedAmount").innerHTML = amount;
    }
    
    function ValidateAmount() {
        // various validationey functions here
        amount = currentControl.value; // save value to collection
        document.getElementById("Subtotal").innerHTML = amount; // update subtotals
        busy = false;
    }
    

提交回复
热议问题