Improve performance with eternal cycle (while true)

I take the data from random remote site like

while(true){
  //take data until I find a document which does not exist in my collection
}

Problem: My site is frozen until there “loops work”

Any good solution how to improve performance?

use a Web Worker maybe?