JavaScript is single-threaded. This causes some problems, for example: No intermediate results. If you call a function that takes a long time to execute, that outputs results periodically, the document's appearance won't be updated until the function completes. I.e. you see all the results at the end, with no intermediate results. (Note: you can use console.log() to output intermediate results.) Solution: setTimeout() and yield. Alternative solution: web workers. Workaround: setTimeout() and refactor the function, so that it uses global variables, indicating what to process next. Workaround: setTimeout() and refactor the function, so that it can input and output information indicating what to process next. Constantly updating icon. You understand that all the results will appear at the end. You don't need any intermediate results. However, the entire time that the function runs, the tab icon redraws (cycles). Solution: call the function via setTimeout().
Multiple variants are presented: 1 variant. All results revealed at the end. The tab icon cycles throughout. The function, raw. 1 variant. All results revealed at the end. The tab icon is static. The function, initialised by setTimeout(). 2 variants. Intermediate results are revealed. The tab icon is static. If the user navigates to another tab, then returns, the webpage is set to blank. The function, refactored drastically, using setTimeout() repeatedly. It uses global variables. The function, refactored slightly to use yield, using setTimeout() repeatedly. 1 variant. Intermediate results are revealed. The tab icon is static. The function, plus a web worker. setTimeout() is not used. The web worker example stores code in a separate 'script' tag, and creates a blob object from it. Another possibility is storing code as a string, and creating a blob object from it. Another possibility is storing code in a separate file, however this requires file access privileges. The examples demonstrate an implementation of the prime counting function, which counts the number of primes between 1 and n. The examples use code from the MDN documentation for an isPrime() function. Source: Array.prototype.filter() - JavaScript | MDN The results should be as follows: Pi(1) = 0 Pi(10) = 4 Pi(100) = 25 Pi(1000) = 168 Pi(10000) = 1229 Pi(100000) = 9592 Pi(1000000) = 78498 Pi(10000000) = 664579 Pi(100000000) = 5761455 The results should match this list: A006880 - OEIS The code takes approximately 100 seconds (1m40s) to run. Press Ctrl+U to view the code. (E.g. works in IE/Firefox/Chrome/Edge.) Examples: Raw [WARNING: the screen will appear blank until completion, and the icon will keep redrawing] setTimeout (single call) [WARNING: the screen will appear blank until completion] setTimeout (multiple calls, refactored) [note: requires a lot of refactoring] setTimeout (multiple calls, yield) [note: requires very minor refactoring] Web Worker [note: requires fairly minor refactoring]