Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: What is the fastest way to click an element a million times [closed]

Tags:

javascript

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...

like image 410
Zach Smith Avatar asked Feb 18 '16 19:02

Zach Smith


Video Answer


2 Answers

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

like image 197
RomanPerekhrest Avatar answered Oct 12 '22 04:10

RomanPerekhrest


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.

like image 34
Jonathan.Brink Avatar answered Oct 12 '22 03:10

Jonathan.Brink