Helper function for setInterval()
Jennifer Fadriquela
Posted on May 30, 2020
There are instances that we need to wait for certain conditions to be satisfied before executing something. Javascript’s setInterval() provides a native timing function that can evaluate an expression over and over again within specified intervals (in milliseconds).
But in my opinion, using setInterval() should be the last resort since there are cleaner ways to wait out results (ex: promises, observables). But in the event that you will use it, please don’t just dump it in your code.
I have faced a scenario where I had used setInterval() too many times that my code became unnecessarily crammed.
You will need 3 things to keep in mind when using this.
- Condition to be satisfied
- Action to be executed when #1 is met
- Clearing the interval after #2 is executed
The common mistake when implementing this is forgetting #3, (I’m guilty!) which will make setInterval() run forever even if satisfying #1.
Since I'm using Angular, I’ve put it in a service so it can be available wherever I would need it.
Here is the code:
import { Injectable } from '@angular/core';
@Injectable()
export class HelperService {
constructor() { }
public runSetInterval(duration: number, condition: any, callback: any): void {
let timer = setInterval(function(){
if (condition())
{
callback();
clearInterval(timer);
}
}, duration);
}
}
In the above, the function required 3 inputs:
- Duration: How many milliseconds to wait before every interval evaluation
- Condition: The expression to be satisfied to stop the interval
- Callback: The task to be executed when #2 is satisfied
Take note that after the callback has been executed, clearInterval() is called immediately. This takes as input the instance of the setInterval() function (defined as timer in above). It will stop the cycle of calling the function again so it won’t run forever.
We can invoke this function like below:
self.helperService.runSetInterval(
1000,
() => {return foo >= 1 && bar === "han solo"},
() => (self.executeSomeTask())
);
Here is a plunkr demo that you can play around.
Posted on May 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024