Ian Zane
Ian Zane

Reputation: 2389

Using setTimeout with intervals less than 1

I'm doing a lot of recursion in Javascript, and to keep the stack from overflowing, I've been using setTimeout. Here's a quick theoretical example:

go(){
    setTimeout(function(){
        x++;
        go();
    },1);
}

I've also got a function logging x to the console every few seconds, but that isn't the concern. What I'm seeing is that no matter what value I put in for the timeout, for which I've used 1 in the example, the script can only run 1000 times per second. I'm doing recursion on the level of hundreds of millions, so this isn't fast enough. When I set the timeout value to 0, or .1, or 1/10, I still only get approximately 1000 times per second. I've tried using 32 and 64 bit browsers (Chrome and Firefox) to no avail.

How can I kick the speed up a notch? Also, I'm relatively new at all of this, so it'd be awesome if the solution was a simple one.

Oh, forgot to mention: if I remove the setTimeout altogether, I overflow the stack every time.

Thanks for the help!

Upvotes: 1

Views: 5830

Answers (4)

user2133061
user2133061

Reputation:

I tried something like you did and found the solution! You don't need recursion and the function setTimeout, but all what you need is to use the setInterval function on the function you want by 1 interval repeatedly in for loop. For example if the for loop repeats itself 10 times, then 10 timers will execute the same function every 4 ms. The code will be executed repeatedly more and more quickly.

Your code should look like this for example:

function onload() {
   for (var i = 0; i < 10; i++)
      setInterval(go, 1);
}
function go() {
   x++;
}

Upvotes: 2

Brian Rogers
Brian Rogers

Reputation: 129657

It's not possible to make setTimeout wait less than 4 milliseconds. That is how setTimeout is defined in the HTML standard (official spec here). More likely your problem is with how your code is structured. Show us the rest of your code, maybe we can help sort it out.

Upvotes: 1

Christophe
Christophe

Reputation: 28114

JavaScript is single threaded, and setTimeout will put your operation at the end of the queue. Even if you reduce the delay, you still have to wait for the previous operations to complete before the one you added kicks in.

Upvotes: 1

Guffa
Guffa

Reputation: 700162

Your solution doesn't lie in making your current code run, but to rethink the code.

I don't know how you are using recursion in your code, but clearly you are using it wrong.

For any reasonable use of recursion, you would be far from overflowing the stack. If you are making recursive calls to a level of hundreds of millions, that is at least a million times too much.

A common approach when using recursion is to divide the work in half for each level. That way you can handle all the items that you can fit in memory without going deeper than about 30 levels.

Upvotes: 4

Related Questions