Counter in M: S format, javascript

2

How to make a counter in JavaScript / jQuery where it is in this 00:00 format and that it stops and executes an action is stopped, but its limit is 10 minutes, it can only stay from 0s to 10 minutes, when it arrives in 10 minutes it automatically stops and executes action even though it has not been manually stopped ...

    
asked by anonymous 14.07.2015 / 02:30

2 answers

4

I started to play with the idea and got to a stopwatch like this:

var Cronometro = function (opcoes) {
    this.opcoes = opcoes || {};
    this.contador = null;
    this.tempo = 0;
    this.configurar = function () {
        this.mostrador = this.opcoes.mostrador || document.querySelector('.mostrador');
        this.iniciar = this.opcoes.iniciar || document.querySelector('.iniciar');
        this.pausar = this.opcoes.pausar || document.querySelector('.pausar');
        this.iniciar.addEventListener('click', this.contar.bind(this));
        this.pausar.addEventListener('click', this.parar.bind(this));
        this.accao = this.opcoes.callback || function () {
            alert('chegou aos dez minutos!');

        }
    }

    this.contar = function () {
        var self = this;
        this.contador = setInterval(function () {
            self.mostrar.call(self, self.tempo++);
        }, 1000);
    }
    this.parar = function () {
        clearInterval(this.contador);
        this.contador = null;
    }
    this.formatarNumeros = function (nr) {
        var str = nr + '';
        return str.length < 2 ? '0' + str : str;
    }
    this.mostrar = function (tempo) {
        var minutos = Math.floor(tempo / 60);
        var segundos = tempo % 60;
        this.mostrador.innerHTML = [minutos, segundos].map(this.formatarNumeros).join(':');
        if (tempo == 36000) {
            this.parar();
            this.tempo = 0;
            this.accao();
            this.contar();
        }
    }

    this.configurar();
    this.contar();
}

jsFiddle: link

It's a recyclable object that has some methods for the features it needs. I wrote in PT so I think most of it explains itself.

You can pass elements to the show / stop / start features , otherwise it has default values that will look for classes .

The part that may need explanation is:

this.contar = function () {
    var self = this;
    this.contador = setInterval(function () {
        self.mostrar.call(self, self.tempo++);
    }, 1000);
}

The setInterval will run in the global scope. This means that if you use this within this function it will point to window . So I used var self = this; to save the reference of my object and use self.mostrar.call(self to call this.mostrar() with this right.

Doing so, recyclable, I can have multiple counters at a time.

    
14.07.2015 / 08:38
2

I made a small function that you can control the time. (JQuery is not necessary for script operation, I just used it to manipulate the textbox and the buttons).

var Clock = {
  minutosStop: 10, //pode "setar"o tempo usando "Clock.minutosStop = 5" para 5 min
  totalSegundos: 0,
  start: function() {
    var self = this;
    this.interval = setInterval(function() {
      self.totalSegundos += 1;
      self.min = Math.floor(self.totalSegundos / 60 % 60);
      self.seg = parseInt(self.totalSegundos % 60);
      if (typeof self.onChange === 'function')
        self.onChange();
      if (self.min == self.minutosStop)
        self.fire();
    }, 1000, self);
    return this;
  },
  toString : function() {
    return String("00" + this.min).slice(-2) + ":" + String("00" + this.seg).slice(-2);
  },
  onChange: null,
  funcaoFire: null,
  pause: function() {
    clearInterval(this.interval);
    delete this.interval;
    return this;
  },
  resume: function() {
    if (!this.interval) this.start();
    return this;
  },
  fire: function() {
    if (typeof this.funcaoFire === 'function')
      this.funcaoFire();
    this.pause();
    this.totalSegundos = 0;
    return this;
  }
};

Clock.start();
Clock.funcaoFire = function() {
  alert(Clock.toString());
}
Clock.onChange = function() {
  $("#contador").val(Clock.toString());
}

$('#pauseButton').click(function() {
  Clock.pause();
});
$('#resumeButton').click(function() {
  Clock.resume();
});
$('#fireButton').click(function() {
  Clock.fire();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><inputid="contador" value="00:00" />
</div>
<div>
  <input id="pauseButton" type="button" value="Pause">
  <input id="resumeButton" type="button" value="Resume">
  <input id="fireButton" type="button" value="Fire">
</div>
    
14.07.2015 / 04:37