Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Calling javascript which uses setTimeout/setInterval

0
0
Hello,
I was able to get this working with a basic example. Then I tried to tweak it to suit my particular needs but I am not having any luck. Technically, I don't specifically need to have the setTimeout function. Instead, any function will do the trick that provides a delayed callback into the script. Also, I don't need the periodic feature as long as I can repeate the delayed function a few times. In my application, the user will be creating counters and when the counter gets to say 5 or 10, they will stop counting until some other event fires to start the counting again. This can be done either with the periodic function or with a delay where the called back function calls the delay again each time until the target value is reached. I prefer the delay in case the user messes up and does not stop the periodic timer - it just seems a little safer.


The trick for me is that I want to do this in a JS class that will be instantiated a hundred times. Each class has its own timer that it uses for counting against its instance data. I tried using setTimeout based upon the solution above and passed this.Run as the callback function. It seemed to me that this lost its context because setTimeout was created in global scope. I'm not all that solid with JavaScript classes and context so I'm not really sure why this didn't work. At one point through my attempted tweaks, I called this.Run on one instance and it ran on all instances. My code looks something like this.
var DVC = function(tag) {
  this.Tag = tag;
  this.timerTarget = 5;
  this.count = 0;
  var _start = false;
  Object.defineProperty(this, 'start', {
    get: function() { return _start; },
    set: function(value) {
             this._start = value;
             if (value === true) { setTimeout(this.Run, 1000);}
           }
  });

  this.Run = function() {
    if (this.count >= this.timerTarget) {
      //do something ...
    }else{
      this.count++;
      setTimeout(this.Run, 1000);
    }
  };
};

var x = new DVC("YV-101");
var y = new DVC("YV-201");

function calledByUser() {
  x.start = true;
}

function someOtherFunction(){
  y.start = true;
}
Any suggestions?

Viewing all articles
Browse latest Browse all 2297