9
Situation
Studying on Thread
, I understood that they are lines of execution within a process.
Studying on Assincronismo em javascript
, I understood that it does not support multiple Thread
, but has a loop de eventos
.
Making an analogy with C would be a memory with addresses, which runs sequentially each address, so when defining a setTimeout({function}, {time})
, would be the same as setar {Function} at the address {team} to be executed.
However as @bfavaretto said in his reply, does not want to say that will execute in {team}, but in the next moment loop de eventos
be free.
Testing
(function(){
var start = null;
var checkTicks = function(){
start = new Date(); // SETA start COM DATA CORRENTE
var s = start.getSplitDate();
start = new Date(s['year'],s['month'],s['day'],s['hours'],s['minutes'],s['seconds']);
setTimeout(showDiff, 1000); // DEFINE FUNÇÃO A SER EXECUTADA APOS 1s
loop(); // CHAMADO DE LOOP QUE DEVE DEMORAR 5s
}
var loop = function(){
var stop = false;
while(!stop){
var current = new Date();
var s = current.getSplitDate();
current = new Date(s['year'], s['month'], s['day'], s['hours'], s['minutes'], s['seconds']);
if(betweenDates(current.toTimestamp(), start.toTimestamp(), 's') > 5){ // SO PARA APOS DIFF DE 5s
stop = true;
}
}
}
var showDiff = function(){
var current = new Date();
var s = current.getSplitDate();
current = new Date(s['year'],s['month'],s['day'],s['hours'],s['minutes'],s['seconds']);
console.log(start.toTimestamp());
console.log(current.toTimestamp());
console.log(betweenDates(current.toTimestamp(), start.toTimestamp(), 's')); // EXIBE DIFERENCA ENTRE start E current
}
checkTicks(); // INICIO O PROCESSO
})();
Console result
6
Doubt
- Why the result was 6 in view of the command
setTimeout(showDiff, 1000);
definedshowDiff
to be executed in 1s? - The
loop de eventos
was occupied by 5s,showDiff
should not be executed immediately after?
Editing
Talking to @bfavaretto again the logic had some inconsistencies because not taken into account the milliseconds of the Date object, to solve this set twice o the variable, in the second without the milliseconds, passing only the relevant values.
Auxiliary
betweenDates
function betweenDates(d1, d2, diff, returnLiteral){
d1 = d1.split(' '); // Divide o timestamp em data e hora
d1[0] = d1[0].split('-'); // Separa as variacoes da data
d1[1] = d1[1].split(':'); // Separa as variacoes da hora
d1 = d1[0].concat(d1[1]); // concatena os dois conteudos formando um array unico.
d1 = new Date(d1[0],d1[1],d1[2],d1[3],d1[4],d1[5]); // gera o objeto date
d1 = Date.UTC(d1.getFullYear(), d1.getMonth(), d1.getDate(), d1.getHours(), d1.getMinutes(), d1.getSeconds()); // retona o time UTC corespondente da data.
d2 = d2.split(' ');
d2[0] = d2[0].split('-');
d2[1] = d2[1].split(':');
d2 = d2[0].concat(d2[1]);
d2 = new Date(d2[0],d2[1],d2[2],d2[3],d2[4],d2[5]);
d2 = Date.UTC(d2.getFullYear(), d2.getMonth(), d2.getDate(), d2.getHours(), d2.getMinutes(), d2.getSeconds());
var dDiff = d2 - d1; // calcula a diferenca entre as datas
var out = {
'y' : dDiff/1000/60/60/24/30/12, // calculo para ano
'm' : dDiff/1000/60/60/24/30, // calculo para mes
'd' : dDiff/1000/60/60/24, // calculo para dia
'h' : dDiff/1000/60/60, // calculo para hora
'i' : dDiff/1000/60, // calculo para minuto
's' : dDiff/1000/1 // calculo para segundo
};
out = Math.floor(out[diff]); // Saida (inteiro do calculo)
// Retorno
if(out < 0 && !returnLiteral){
return out*-1;
}else{
return out;
}
}
Date.prototype.getSplitDate
Date.prototype.getSplitDate = function(){
var day = this.getDate();
var month = this.getMonth();
var year = this.getFullYear();
var hours = this.getHours();
var minutes = this.getMinutes();
var seconds = this.getSeconds();
var o = {};
o['day'] = day;
o['month'] = month;
o['year'] = year;
o['hours'] = hours;
o['minutes']= minutes;
o['seconds']= seconds;
return o;
}
Date.prototype.toTimestamp
Date.prototype.toTimestamp = function(short){
var o = this.getSplitDate();
var date = '####-##-## ##:##:##';
date = o['year'].toString().lpad(0,4).mask(date);
date = o['month'].toString().lpad(0,2).mask(date);
date = o['day'].toString().lpad(0,2).mask(date);
date = o['hours'].toString().lpad(0,2).mask(date);
date = o['minutes'].toString().lpad(0,2).mask(date);
date = o['seconds'].toString().lpad(0,2).mask(date);
if(short){
date = date.split(' ');
return date[0];
}else{
return date;
}
}
String.prototype.Mask
String.prototype.mask = function(mask){
var value = onlyNumber(this);
for(var i = 0; i <= mask.substrCount('#'); i++){
if(typeof(value[i]) === 'undefined'){
break;
}
var k = mask.indexOf('#');
mask = mask.split('');
mask[k] = value[i];
mask = mask.join('');
}
return mask;
}
@bfavaretto, if possible would like your analysis.
– Guilherme Lautert
What you have here: betweenDates. Could put the contents of this method also?
– Emir Marques
@Emirmarques is a great method, I believe have no relevance to this issue, what it does is basically compares two
string
formattimestamp
and pick up the difference in seconds. But if you want to see the method, because you may be interested, I assemble a question about and put as answer.– Guilherme Lautert
Could be the rounding of the
betweenDates
, No? Maybe I did5.x
.– bfavaretto
@bfavaretto really has a
Math.floor
, but how is second ends up becoming whole, anyway. I edited , putting the function– Guilherme Lautert
What is
.toTimestamp()
?– Sergio
And when you use
betweenDates(current.toTimestamp(), start.toTimestamp(), 's')
the argumentdiff
within the functionbetweenDates
it’s gonna be a string... that’s what you want?– Sergio
@Sergio I think now has all the functions involved, as for the diff, yes a string
– Guilherme Lautert