0

I'm experimenting a timer (Javascript Type). I use an interval instead of timeout. Therefore I made a Timer Type with three parameters: duration in milliseconds, interval in milliseconds and a JQuery object which is attached to the timer. Within my initTimerPlugin() function I create a JQuery Object, which is not added to a DOM-structure yet (just to try if the events I try to raise, work), I also initialize my global TIMER of a Timer Type, where I define the duration of 30 seconds, an interval of 1 decisecond and attach my JQuery timer to my TIMER. Then I call my start function (which is a function of my Timer Type). It sets an interval and calls the tick function and I expect it to tick as long as the total duration is not equal to 0. The problem is, it ticks only once.

I know there are lots of questions and answers about intervals in StackOverflow, but none of them use a Type to implement a timer, and I cannot find a solution for my problem. Could anyone explain what's the reason my timer doesn't keep tick-ing.

var TIMER;

var Timer = function (ms, interval, $timer) {
    this.ms = ms;
    this.interval = interval;
    this.$timer = $timer;
    this.counter = null;


    this.start = function () {
        this.counter = window.setInterval(this.tick(), this.interval);
    };

    this.tick = function () {
        this.ms -= this.interval;
        console.log(this.ms);
        this.trigger('tick');
        console.log("ticking...");
        if (this.ms < 0) {
            this.ms = 0;
        }
        if (this.ms == 0) {
            window.clearInterval(this.counter);
        }
    };

    this.hold = function () {

    };

    this.expire = function () {

    };

    this.trigger = function (event) {
        if (typeof event === 'string') {
            var e = jQuery.Event(event);
            this.trigger(e);
        } else {
            this.$timer.trigger(event);
        }
    }
};

var initTimerPlugin = function () {
    var $timer = $('<div class="timer">');
    TIMER = new Timer(30000, 100, $timer);
    $timer.on('tick', function () {
        console.log('hello world');
    });
    TIMER.start();

};

$(document).ready(initTimerPlugin);

FYI: the JQuery version I use is 3.2.1.

LowLevel
  • 1,085
  • 1
  • 13
  • 34

0 Answers0