6

I'm doing this fun coding challenge that I found at a meetup (doyouevendev.org)

What is the fastest way to generate a million clicks on an element? The coding challenge seems to be centred around the inspector, which I'm finding worthwhile.

My code (that i'm executing in chrome command line):

var item = document.getElementsByClassName("clicky-button pulse");
var item = item[0];
count = 0;
(function clickIt() {
    count += 1
    setInterval(function changeClicks() {
        item.click();
    }, 1);
    if (count <= 50) {
        clickIt();
    };
})();

I suspect there's a better way... It actually seems to be slowing down...

Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • 1
    How about to split it into few threads? – Viktor Feb 18 '16 at 19:25
  • 10
    "What is the fastest way to click an element a million times" - get a LOT of interns :) – max Feb 18 '16 at 19:25
  • do you mean set up web workers or something similar? @ViktorDanilov – Zach Smith Feb 18 '16 at 19:27
  • I'm pretty sure web workers don't have access to the DOM. – Andy Feb 18 '16 at 19:28
  • Can't you just use a `for` loop? `for (var i = 0; i < 1e6; i++) { item.click(); }`. JS doesn't have threads and, as was pointed out, workers can't access the DOM. – Mike Cluck Feb 18 '16 at 19:30
  • I've completed the game and actually clicking it isn't the way to beat that level. The instructions even tell you not to. – darryn.ten Feb 20 '16 at 10:50
  • Yeah I found it. Now in stuck in level 3.this is partly because I don't really understand the concept of sockets, frames, ddp, etc. Do you have any helpful hints? – Zach Smith Feb 20 '16 at 12:32
  • @darryn.ten - yes, but changing the value to 1 000 000 didn't do anything. which is why i resorted to this, before trying 999 999 + 1 click – Zach Smith Jun 29 '17 at 21:59

2 Answers2

15

The 'negative' while loop should be slightly faster:

var i = 1000001;
while (--i) {
   item.click();
}

Choose one: http://www.stoimen.com/blog/2012/01/24/javascript-performance-for-vs-while/

Javascript Performance: While vs For Loops

Community
  • 1
  • 1
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
5

JavaScript is single-threaded so keep it simple:

for (var i = 0; i < 1000000; i++) {
    item.click();
}

EDIT: Looks like @romanperekhrest's answer may be slightly faster since it's using a decrementing while loop.

Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115