Search code examples
javascriptalgorithmweb-worker

Javascript code for making my browser slow down


I'm writing a library for WebWorkers, and I want to test the difference between running a script in the main page thread, versus in one or more workers. The problem is: I can't find out of hand a short function which will strain my browser enough that I can observe the difference.

A quick search didn't return much, but it might just be that I don't really know what to search for; usually I try to optimise my code, not make it slower...

I'm looking for algorithms or patterns that can be easily implemented in pure Javascript, that do not depend on the DOM or XHR, and which can have an argument passed to limit or specify how far the calculation goes (no infinite algorithms); 1s < avg time < 10s.

Extra points if it can be built without recursion and if it does not incur a significant memory hog while still being as processor intensive as possible.


Solution

  • /**
     * Block CPU for the given amount of seconds
     * @param {Number} [seconds]
     */
    function slowdown(seconds = 0.5) {
      const start = (new Date()).getTime()
      while ((new Date()).getTime() - start < seconds * 1000){}
    }
    
    slowdown(2)
    console.log('done')

    Calling this method will slow code down for the given amount of seconds (with ~200ms precision).