DEV Community

Cover image for Control the speed of the JavaScript loop (Throttle).
Farzad Aziminia
Farzad Aziminia

Posted on • Updated on

Control the speed of the JavaScript loop (Throttle).

Welcome to "Javascript: Tricks and tips" In this series of blogs, I'll show you some development tips and will solve some of the problems that I've faced during my career as a Software engineer.

JavaScript is one of the most popular programming languages. it’s dominated the web world and gaining popularity outside of the web. Node.js opened the door to the backend and Cordova took it into mobile.

It first appeared back in 1995 and it’s evolving since. Because of its age, there are so many different coding styles and development paradigms out there. One of the challenges that we may face during our development is: how can we control the speed of JavaScript loops? Although there are several different ways to achieve that, today I’ll discuss my favorite approach.

But first Let’s start with basic loops in javaScript:

For loop

For loop is the most basic and powerful way of running a block of code a number of times. We will not get into the gory details, but basically, a for loop is consists of a starting variable, end condition, and increments or negative increments statement.

console.log('start');
const count = 3;
for (let i = 0; i <= count; i++){
   console.log(i);
}
console.log('end');

output

start
0
1
2
3
end

Now we have our basic for loop, Let’s see how we can control the speed of that loop. One way to you can accomplish that goal is, wrap your console.log around setTimeout. But first, let’s talk about the setTimeout method and see how we can utilize that to achieve our goal.

setTimeout

setTimeoiut is one of the many native Javascript methods that enables scheduling execution of a given function in the future time. The method accepts a function, number in milliseconds, and optional parameters. For example:

console.log('start');

const myFunction = (parameter)=>{
 console.log('myFunction is called with parameter => ' + parameter)
}

setTimeout(myFunction, 2000, 'Book')

output:

start
myFunction is called with parameter => Book

As you can see, the “myFunction” function scheduled to execute in 2 seconds (2000 milliseconds) with “Book” as its parameter. After the function gets called, it prints “myFunctions is called with parameter => Book”.
The part that I want to emphasize is the parameters that you can pass to the function. You can do so many things with those parameters. With that in your mind, let’s re-write our for loop:

console.log('start');
const count = 3;
for (let i = 0; i <= count; i++){
  console.log('Block:' + i);
  setTimeout((ix)=>{
     console.log(ix);
  }, 1000 * i, i)
}
console.log('end');

output:

start
Block:0
Block:1
Block:2
Block:3
end
0
1
2
3

If you look at the outputs, you can see for each iteration, console.log gets scheduled for (“i” * 1000) in the future, with “i” passed as a parameter. So for the first iteration “i” is zero and console.log scheduled for immediate execution. The second time “i” is 1 and console.log scheduled for execution in 1 second and …. Next, we will talk about one of my favorite subjects in computer programming “Recursion”

Recursion

A recursive function is a function that calls itself in order to repeat a block of code to solve a problem. In the following code snippet, you can see how I iterated from 0 to 3.

console.log('start');
function loop(index, count){
   console.log(index);
   if (index < count){
       index ++;
       loop(index, count);
   }
}

loop(0, 3);
console.log('end');

output:

start
0
1
2
3
End

Now it’s the time to control the speed of our recursive function:

console.log('start');
function loop(index, limit, count){
  console.log('block:' + index);
  console.log(index);
  if (index < count){
      index ++;
      setTimeout(()=>{
          loop(index, limit, count);
      }, limit)
  }
}
loop(0, 1000, 3);
console.log('end');

output:

start
Block:0
0
end
Block:1
1
Block:2
2
Block:3
3

Hooray! But wait! As you can see the problem of our approach is, “end” gets printed after our first iteration. That’s because of the async nature of the javascript and how javascript manages its call stack. I don’t get into detail, but I’ll show you how you can fix it.

console.log('start');
function loop(index, limit, count){
   console.log(index);
   if (index < count){
       index ++;
       setTimeout(()=>{
           loop(index, limit, count);
       }, limit)
   } else {
       printEnd();
   }
}

loop(0, 1000, 3);

function printEnd(){
   console.log('end');
}

output

start
0
1
2
3
end

Let’s go through the steps to find out what happens once we run the code:

  1. Start gets printed.
  2. line 15 executes loop function and passes 0 as its parameter.
  3. index gets printed which at this point is 0.
  4. index is still 0 so our if statement returns true, index incremented by 1 and by using setTimeout function, we schedule our recursion to be executed in 1 second.
  5. index gets printed which at this point is 1.
  6. the Same pattern repeats until ”I” gets to 3
  7. index is 3 so our if statement returns false, now our else statement gets executed and it’s calling “printEnd” function which prints “end“.

Conclusion

There are different ways to control the speed of Javascript Loop. Today we talked about two different ways of achieving that goal. We also discussed the setTimeout method and how it relates to our topic. We talked about recursion in general and how we can use that to loop. It’s really up to you which approach do you wanna take to throttle your loop, both works just fine, it depends on your use case.

In my next post, I will talk about the environmental variables. Stay tuned.

Top comments (0)