nltimer

Timer can change own period

HTML

<div id="test"></div>

CSS

#test {
    position: absolute;
    top: 0px;
    left: 20px;
    height: 20px;
    width: 20px;
    border: solid black 1px;
    border-radius: 10px;
}

JavaScript

nonLinearTimer = {
    _period: 1000,
    _onNonLinearTimerEvent: null,
    _empty: function () {},
    _mode: null
}

nonLinearTimer.Start = function () {
    setTimeout(nonLinearTimer._mode, nonLinearTimer._period);
    nonLinearTimer._onNonLinearTimerEvent();
}

nonLinearTimer.Stop = function () {
    this._mode = this._empty;
}

nonLinearTimer.Prepare = function () {
    this._mode = this.Start;
}

nonLinearTimer.setHandler = function (f) {
    this._onNonLinearTimerEvent = f;
}

nonLinearTimer.setPeriod = function (p) {
    this._period = p;
}

var down = function () {
    $('#test').css({
        top: '+=1px'
    });
    myTimer.setPeriod(500 / tick);
    if (tick == 300) {
        myTimer.Stop();
        myTimer.setHandler(up);
        myTimer.Prepare();
        myTimer.Start();
    }
    tick++;
}

var up = function () {
    $('#test').css({
        top: '-=1px'
    });
    myTimer.setPeriod(500 / tick);
    if (tick == 1) {
        myTimer.Stop();
        myTimer.setHandler(down);
        myTimer.Prepare();
        myTimer.Start();
    }
    tick--;
}

var tick = 1;
myTimer = nonLinearTimer;
myTimer.setHandler(down);
myTimer.setPeriod(500);
myTimer.Prepare();
myTimer.Start();