TIMERS TIMERS TIMERS TIMERS

TIMER Class, instantiate via jQuery event handlers.......

by lasha

HTML

<a href="#" class="addNewTimer">ADD NEW TIMER</a>

JavaScript

var timerInstances = [];
var instanceCounter = 0;

var TIMER = function(interval, $elToIncrement, callback){
    var expose = {};
    
    expose.whichInstance = ++instanceCounter;
    
    expose.internalCounter = 0;
    
    expose.startTimer = function(){
        setInterval(function(){
            //console.log("timer triggered every " + interval / 1000 + " seconds");
            expose.internalCounter++;
            
            $elToIncrement.find('.timeCount').html(expose.internalCounter);
            
            callback(expose.whichInstance, expose.internalCounter);
        },interval);
    }
    
    expose.endTimer = function(){
        clearInterval(this.startTimer);
    };
    
    return expose;
}

$(".addNewTimer").click(function(e){
    e.preventDefault();
    
    var $elToIncrement = $('<div />', {
        "class": 'test',
        html: "<div>" + (instanceCounter + 1) + ". Click to start timer: <span class='timeCount'>0</span></div>"
    }).appendTo("body");
    
    var indexOfThisTimer = instanceCounter;
    timerInstances.push(new TIMER(1000, $elToIncrement, function(instance, seconds){
        console.log("tick from instance " + instance, seconds + " seconds have passed");
    }));
    
    // console.log(indexOfThisTimer);
    
    $elToIncrement.click(function(e){
        // console.log(this);
        timerInstances[indexOfThisTimer].startTimer();
    });
});


//timerInstances.push(new TIMER(2000, function(instance){
//    console.log("tick from instance " + instance);
//}));

//timerInstances.push(new TIMER(2000, function(instance){
//    console.log("tick from instance " + instance);
//}));

//var randomCounter = 0;

//setTimeout(function(){
//    timerInstances[0].endTimer();
//},5000)

//var firstTimer = new TIMER(2000, function(){ 
//    randomCounter++;
//    console.log(randomCounter);
//});

//setTimeout(function(){
//    firstTimer.endTimer();
//},10000);