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."));