I wanted to build a search that shows you the results when the user finishes writing.
If I had to search in a local db I would have triggered the search every time the user releases a key.
In my case I have to send Web Requests to an API point that exposes the search function. The server allows only 20requests per minute from a single IP.
So, I wrote a Thread that detects when user really finishes writing:
- (while true)
- save the searchbox text
- wait for 400ms
- check if the searchbox text is the same as the one saved before
Code:
private void checkIfUserFinishedWritingFunction() {
while(true) {
String previousText = textField.getText();
try {
Thread.sleep(400);
} catch (InterruptedException ex) {
return;
}
String actualText = textField.getText();
//WHEN USER FINISHED WRITING...
if(previousText.equals(actualText)) {
//IF SEARCHBOX ISN'T EMPTY
if(!textField.getText().trim().isEmpty()) {
//START A THREAD THAT SENDS WEB REQUEST
}
//IF SEARCHBOX IS EMPTY...
else {
//HIDE RESULTS POPUP
if(resultsList.isShowing())
resultsList.hide();
}
return;
}}}
NetBeans is telling me that Thread.sleep() called in loop could be dangerous. I think it's because of the cost, and in my the loop runs every 400ms.
How can I fix this algorithm?