I have a button that when clicked calls a function – this function does some asynchronous Ajax and alerts a messagebox when the Ajax has returned. I do not want the user clicking on the button multiple times – if he clicks on the button when the Ajax has not returned then an error message should be alerted.
I know that this can be easily done using a global boolean variable (set it initally to true, make the ajax call and set it to false – set it again to true when the ajax returnes – check if the global is false when the user clicks the button). Also it can be done similarly if instead of the window/global object I use another global object containing the function and the boolean
However, I do not like very much the above methods – I think that they are a little old-school-Javascript. I was wondering if there was a more elegant way to do it, for instance using JS closures !
Using this method, your variable will not leak to the global scope. There’s no way to manipulate this variable from outside the function:
Others may suggest setting a property of the function, but this property can easily be adjusted from outside, which is not desirable.