﻿
function timeSpanContainer(timeOut)
{
    this.__timeOut = timeOut ? timeOut : 1000;

    this.spanList = new Array();
    
    this.currentIndex = 0;

    this.timeOutCache = null;
};

timeSpanContainer.prototype.AddAction = function(callback)
{
    if (typeof callback == "function")
    {
        this.spanList.push(callback);

        return true;
    }

    return false;
};

timeSpanContainer.prototype.Execute = function()
{
    if (this.spanList.length == 0)
    {
        this.stop();

        return;
    }

    var index = this.currentIndex;

    if (index >= this.spanList.length)
    {
        index = 0;
    }

    try
    {
        this.spanList[index]();
    }
    catch (e) { }

    this.currentIndex = index + 1;
};

timeSpanContainer.prototype.start = function()
{
    if (this.timeOutCache == null)
    {
        var outer = this;

        var doOnTimeOut = function()
        {
            outer.Execute();
        };

        this.timeOutCache = setInterval(doOnTimeOut, outer.__timeOut);
    }
};

timeSpanContainer.prototype.stop = function()
{
    if (this.timeOutCache != null)
    {
        clearTimeout(this.timeOutCache);

        this.timeOutCache = null;
    }
};

var __TimeSpan = new Array();

function TimeSpan(key, _timeOut)
{
    for (var i = 0; i < __TimeSpan.length; i++)
    {
        if (__TimeSpan[i].key == key)
        {
            return __TimeSpan[i].value;
        }
    }

    var item = new Object();

    item.key = key;

    item.value = new timeSpanContainer(_timeOut);

    __TimeSpan.push(item);

    return item.value;
};
