Warn when one time is different from the other

2

Hello, I have two vars storing two times in the format minutos:segundos:milisegundos :

var tempo1 = "11:10:10";
var tempo2 = "11:10:10";

I would like to generate an alert when tempo1 is dirent (greater or less) in 0.5sec of tempo2 .

    
asked by anonymous 02.11.2017 / 04:42

2 answers

5

If your input is minutos:segundos:milisegundos you can know if the difference between the two is less than 300ms for example like this:

function diff300(a, b) {
  a = a.split(':').map(Number);
  b = b.split(':').map(Number);
  return Math.abs(
      new Date(2000, 0, 1, 1, ...a) - new Date(2000, 0, 1, 1, ...b)
  ) > 300;
}

console.log(diff300("11:10:10", "11:10:10")); console.log(diff300("11:10:10", "11:10:510"));

The idea is to create two dates with the minutes, seconds and milliseconds as the only difference and then check if the absolute difference between them is less than 300ms

    
02.11.2017 / 08:05
5

More below is an alternative answer and shorter . E also more economical in features.

The function gets three arguments, in order:

  • time 1
  • time 2
  • value to be compared in milliseconds (500, in this case)

If you do not need something generic (always 500ms), you can remove the 3rd argument. But do not forget to swap in all places within the function, appropriately, by 500 where there was the name of the third argument.

When converting times to Date , false data must be entered for time zone and day, month and year. It does not interfere with the result since these extra data are the same for both cases.

The function returns true for cases where the difference is greater or less than the value specified in the 3rd argument. Returns false if it is exactly and equal to the specified value.

The way you handle the result is to the liking of the customer. If you want to use alert() or other features, just change.

// Tempos armazenados a serem verificados
var tempo_1 = "13:12:11";
var tempo_2 = "13:12:12";

// Função verificadora de diferença
function dif_ms(tempo_1, tempo_2, comparativo) {

  // Converte os tempos para o tipo 'Date' e obtme tempo total em milissegundos
  var t1 = new Date("2000-01-01T" + tempo_1 + "Z").getTime();
  var t2 = new Date("2000-01-01T" + tempo_2 + "Z").getTime();

  // Verifica a diferença
  var delta = Math.abs(t1 - t2);

  // Retorna 'true' se for diferente (maior ou menor) que 500ms ou 0.5s
  return delta != comparativo;

}

// Exemplo de saída
console.log("- É diferente de 500ms (ou 0,5s)? \n- " + (dif_ms(tempo_1, tempo_2, 500) ? "Sim." : "Não."));
    
02.11.2017 / 08:05