1

How to make a script repeat it self faster than a setTimeout allows but still not as fast as possible?

Check this demo for 2 examples. (I post the demo code under also)

var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');

document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);

function go() {
    x++;
    divEl.innerHTML = x;
    if (x > 100) {
        return false;
    }
    setTimeout(function () {
        go();
    }, 0);
}

function go2() {
    x++;
    divEl2.innerHTML = x;
    if (x > 100) {
        return false;
    }
    go2();

}
Rikard
  • 7,485
  • 11
  • 55
  • 92
  • 4
    A plain for loop would be faster....What in the world are you trying to accomplish? – epascarello Jul 29 '13 at 13:30
  • 1
    @epascarello, a loop is a good answer. I am just moved by curiosity of understanding javascript better. I had once a code that rendered a line too slow with setTimeout and too fast without it. – Rikard Jul 29 '13 at 13:33
  • Possible duplicate of [Is there anything faster than setTimeout and requestAnimationFrame?](https://stackoverflow.com/questions/19906947/is-there-anything-faster-than-settimeout-and-requestanimationframe) – Pacerier Aug 12 '17 at 08:16

2 Answers2

2
var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');

document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);

function go() {
    x++;
    divEl.innerHTML = x;
    if (x > 100) {
        return false;
    }
    if (x % 2 == 0) {
     setTimeout(function () {
         go();
     }, 0);
    } else {
     go();
    }
}

function go2() {
    x++;
    divEl2.innerHTML = x;
    if (x > 100) {
        return false;
    }
    go2();

}

Two times faster, but not as fast as possible =)

Maxim Pechenin
  • 344
  • 1
  • 13
1
var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');

document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);

function go() {
    divEl.innerHTML = ++x;
    if (x > 100) {
        return false;
    }
    if (x % 5 == 0) {
     setTimeout(function () {
         go();
     }, 0);
    } else {
     go();
    }
}

function go2() {
    x++;
    divEl2.innerHTML = x;
    if (x > 100) {
        return false;
    }
    go2();

}
Hamed Khosravi
  • 535
  • 7
  • 21