1

I am looking for an OOP solution to have the same object literal/class running in parallel or nested, without interfering with the variables of other instances.

I created a demo in jsfiddle with some buttons to show the desired functionality, I tried to pass an id to call the setTimeout actions independently, but I realize that all variables are also shared between different instances

(function( skillet, $, undefined ){
  var t;
  var timer_is_on = 0;
  var startingPoint = 0;
  var endingPoint = 99;
  var timerLapse = 1000;
  var timerMatrixIndex = 0;
  var timerMatrix = [1000];
  var callback;

  function timedCount(timerLapse) {
    console.log(timerMatrix[timerMatrixIndex]);
    if (startingPoint > endingPoint || timer_is_on === 0) {
      clearTimeout(t[timerId]);
      skillet.stopCount();
    } else {
      document.getElementById("txt").value = startingPoint;
      if (timerMatrixIndex+1 < timerMatrix.length) {
        timerMatrixIndex++;
      }  
      startingPoint++;
      callback();
      t = { timerId: setTimeout( function() {timedCount(timerMatrix[timerMatrixIndex]);} ,timerLapse) }; 
    }
  }

  skillet.startCount = function(options) {
    options = options || {}; 
    startingPoint = options.startingPoint || 0; 
    endingPoint = options.endingPoint || 100;
    timerMatrix = options.timerMatrix || [1000];//[ 25,25,50,50,50,100,100,100,150,150,200,200,300,400,500,600,700,800,1000 ];
    timerId = options.timerId || 0;
    callback = options.callback || function(){};
    timerMatrixIndex= 0 ;

    if (!timer_is_on) {
      timer_is_on = 1;
      timedCount(timerMatrix[0]);
    }
  }

  skillet.stopCount = function() {
    clearTimeout(t[timerId]);
    timer_is_on = 0;
  }
}( window.skillet = window.skillet || {}, jQuery ))

I am looking an elegant way, not just adding "myid" to all methods or properties, probably I should had created a class instead of an object literal but I am just learning Javascript OOP.

It's there a simple way to do it?

https://jsfiddle.net/phrad/ut4yde9p/1/

As in the example the "callback count myid" should be independent of the other instances using the default (no id included)

Right now every call nulls the parameters of the previous call

Phra
  • 21
  • 4
  • 1
    Your first paragraph statement is slightly contradictory. You're asking how to have the *same* object run in parallel with itself...., not conflict with *other* instances. If there are multiple instances, it's not the *same* object. And if the variables are scoped to the object, they will not conflict with each other. – Taplar Apr 12 '19 at 15:14
  • @Taplar Thank you, I tried to define the problem the best as possible, I am not sure neither how this is internally executed. – Phra Apr 12 '19 at 17:26

0 Answers0