Preventing "race conditions" with jQuery AJAX calls

I’m currently learning a somewhat obscure foreign language so I made a simple site (http://ianburris.com/armenian/) so that I could easily look up words from the book used in my class. One thing I’ve noticed is that sometimes if I enter something like “house” the request for words that match “h” will finish after the request for “ho” and thus the results for “h” will overwrite the results for “ho”. This is especially apparent if you type in a word and then hit the backspace really fast. After you’ve cleared out all the characters my message saying “Enter an English word” will pop up for a second and then the last AJAX request finally completes overwriting the message. Is there a way to essentially cancel the AJAX calls or should I include a timestamp that I can use to throwout results that are out of date?

Add Comment
1 Answer(s)

Maintain a variable to identify the order number of ajax call being made,
eg. 1 for first call, 2 for second call,3 for ajax call for 3rd letter.
And whenever the ajax request is complete, check current string length of the value of your input box.
If they match, data is valid, write it in your page, else reject it.

example:
ajax request with value 3 is completed,
current value in input box = “hou” , since hou.length == 3 , it is a correct match, and data can be processed.

Answered on July 12, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.