Preventing race conditions with jQuery AJAX calls

I am currently learning a somewhat obscure foreign language, so I made a simple site ( http://ianburris.com/armenian/) so that I can easily find the words from the book used in my class. One thing I noticed is that sometimes, if I enter something like “home”, the query for words matching “h” will be completed after the query for “ho”, and so the results for “h” will be overwrite the results for "ho". This is especially noticeable if you enter a word and then quickly remove the backspace. After you clear all the characters, my “Enter English word” message will appear for a second, and then the last AJAX request will finally complete the message rewriting. Is there a way to substantially cancel AJAX calls, or include a timestamp that I can use to display outdated results?

+3
source share
1 answer

Keep a variable to determine the ajax call order number, for example. 1 for the first call, 2 for the second call, 3 for the ajax call for the third letter. And whenever the ajax request is completed, check the current string length of the value of your input field. If they match, the data is valid, write them on your page, and then reject.

Example: an ajax request with a value of 3 is completed, the current value in the input field = "hou", since hou.length == 3, this is a correct match, and the data can be processed.

+5
source

Source: https://habr.com/ru/post/1791871/


All Articles