Anyone that's ever tried to wrangle the native javascript interval timer has thought, "Why does this have to be so ugly and unmanageable?" MorphInterval provides a simple but flexible solution to managing javascript interval timers.
This example shows a simple interval that calls the doSomething() function once every 60 seconds
var thisObj = this;
this.refreshInterval = new window.MorphInterval(
{
minInterval: 60,
maxInterval: 60,
curve: 'flat',
callback: function()
{
thisObj.doSomething.call(thisObj);
}
}).start();
Killing the interval is easy, just call the kill() method:
this.refreshInterval.kill();
With a constant interval, you might wonder why this is any better than just using the native implementation. But what if you want the interval to morph over time. For example, let's say you need to poll an api for updates (news feed, for example), but those updates come in irregular bursts, and you don't want to keep pestering the server when there hasn't been any activity for a while. For this you would want to have an exponential growth type of interval, where you start out checking every 5 seconds but check less frequently as time passes and you don't get a response. And then, when you do get a response, you will probably be getting another one soon, so you want to reset and start checking more frequently. As long as responses keep coming, you want to display them responsively. This is just one use case. So let's take a look at how you would implement this:
var thisObj = this;
this.refreshInterval = new window.MorphInterval(
{
minInterval: 5,
maxInterval: 60,
curve: 'exponentialGrowth',
callback: function()
{
thisObj.doSomething.call(thisObj);
}
}).start();
This is going to instantiate a morphing interval that starts out calling the doSomething() method every 5 seconds, but the interval exponentially increases until it flattens out at its max of 60 seconds. If desired you could also provide a rate of change as a percentage. The default is 5% (0.05). If you wanted to reset the interval, you would simply do something like this:
if (condition)
{
this.refreshInterval.reset();
}
I wrote this utility class a few years ago to reduce the frustration I was feeling trying to manage the native javascript intervals, which I found to be inflexible and too easy for lazy programmers to mismanage, often resulting in excessively multiplying intervals that didn't get terminated. This implementation forces OOP practices, adds useful functionality, and makes it easy to manage.
GPL