Counter in M:S format, javascript

Asked

Viewed 162 times

2

How to make a counter in Javascript/jQuery where it is in this format 00:00 and that it stops and performs an action is stopped, but its limit is 10 minutes, can only stay from 0 until 10 minutes, when you reach the 10 minutes it automatically stops and performs action even if it has not been stopped manually...

2 answers

4


I played with the idea and came to a time 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: http://jsfiddle.net/1f32wtsm/

It is a recyclable object that has some methods for the functionalities it needs. I wrote in PT so I think most of them explain themselves.

You can pass elements to the show/stop/start features, if it does not have default values it will look for classes.

The party that may need an 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. That means using this within this function it will point to the window. So I used var self = this; to store the reference of my object and use self.mostrar.call(self to call this.mostrar() with the this right.

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

  • 2

    Well, you like to play with what you design, I’m like that too! , It worked in perfect harmony, I really liked it because the way Oce set up the function made it malleable and easy to manipulate, It was great, I made great adaptations, Thank you so much for adding my knowledge and helping me =D

  • @Elaine I’m glad I could help!

2

I did a little function that you can control time. (Jquery is not required for script operation, I only used to manipulate textbox and 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>
  <input id="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>

  • 1

    Great code! Very good the way that Voce applies the execution methods, super formidable, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.