Home > Mobile >  How to console log numbers from 1 to 1 million efficiently
How to console log numbers from 1 to 1 million efficiently

Time:02-04

Javascript code that prints out (using console.log) a sequence of numbers from 1 to 1,000,000 without blocking the interactions with the browser. For example, while that piece of Javascript is running, mouse, keyboard events etc should work fine and browser doesn't hang.

CodePudding user response:

I think your best option would be putting all those numbers in a array, then console logging that array, if you are using a browser with decent developer tools it should split up the array into ~50 element chunks.

Alternatively you could add a short wait between each console log I would expect at some point your browser with start to hang again.

CodePudding user response:

You can create a Web worker and let it handle your request in the backend

In your html file

index.html

<script>
 // Check if your browser supports worker
 if (window.Worker) {

 var worker = new Worker('worker.js');
 worker.postMessage("Start Logging");
 }
</script>

worker.js

onmessage = function(e) {
  const result = e.data;
  if(result == "Start Logging"){
    for(let i = 1; i<= 1000000;i  ){
      console.log(i)
    }
    postMessage('Done Loggind')
  }
  
}

Web Workers can run your script in background without intercepting your main thread

  •  Tags:  
  • Related