Foros del Web » Programando para Internet » Javascript »

Décimas de segundo en un número entero

Estas en el tema de Décimas de segundo en un número entero en el foro de Javascript en Foros del Web. Por lo visto no hay una función get que devuelva décimas de segundo, tan solo segundos o milisegundos. Pero encontré este sencillo truco para obtenerlas: ...
  #1 (permalink)  
Antiguo 17/08/2011, 06:24
Avatar de ThunderWolf  
Fecha de Ingreso: julio-2011
Mensajes: 30
Antigüedad: 12 años, 9 meses
Puntos: 1
Décimas de segundo en un número entero

Por lo visto no hay una función get que devuelva décimas de segundo, tan solo segundos o milisegundos. Pero encontré este sencillo truco para obtenerlas:

getMilliseconds() / 100

El problema es que el formato en que lo devuelve es 0,00. A efectos prácticos, siguen siendo milisegundos con una coma de por medio.

¿Como podría convertirlo en un único numero entero?

El contador es el siguiente (muestra el resultado en un div id="counter"):

Código Javascript:
Ver original
  1. /**********************************************************************************************
  2. * CountUp script by Praveen Lobo (http://PraveenLobo.com/techblog/javascript-countup-timer/)
  3. * This notice MUST stay intact(in both JS file and SCRIPT tag) for legal use.
  4. * http://praveenlobo.com/blog/disclaimer/
  5. **********************************************************************************************/
  6. function CountUp(initDate, id){
  7.     this.beginDate = new Date(initDate);
  8.     this.countainer = document.getElementById(id);
  9.     this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
  10.     this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
  11.     this.hours = 0, this.minutes = 0, this.seconds = 0, this.milliseconds = 0;
  12.     this.updateNumOfDays();
  13.     this.updateCounter();
  14. }
  15.  
  16. CountUp.prototype.updateNumOfDays=function(){
  17.     var dateNow = new Date();
  18.     var currYear = dateNow.getFullYear();
  19.     if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
  20.         this.numOfDays[1] = 29;
  21.     }
  22.     var self = this;
  23.     setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
  24. }
  25.  
  26. CountUp.prototype.datePartDiff=function(then, now, MAX){
  27.     var diff = now - then - this.borrowed;
  28.     this.borrowed = 0;
  29.     if ( diff > -1 ) return diff;
  30.     this.borrowed = 1;
  31.     return (MAX + diff);
  32. }
  33.  
  34. CountUp.prototype.addLeadingZero1=function(value){
  35.     return value < 100 ? ("0" + value) : value;
  36.  
  37. }
  38.  
  39. CountUp.prototype.addLeadingZero2=function(value){
  40.     return value < 10 ? ("0" + value) : value;
  41.  
  42. }
  43.  
  44. CountUp.prototype.formatTime=function(){
  45.     this.milliseconds = this.addLeadingZero1(this.milliseconds);
  46.     this.milliseconds = this.addLeadingZero2(this.milliseconds);
  47.  
  48. }
  49.  
  50. CountUp.prototype.calculate=function(){
  51.     var currDate = new Date();
  52.     var prevDate = this.beginDate;
  53.     this.milliseconds = this.datePartDiff(prevDate.getMilliseconds(), currDate.getMilliseconds(), 1000);
  54.     this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
  55.     this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
  56.     this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
  57.     this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
  58.     this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
  59.     this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
  60. }
  61.  
  62. CountUp.prototype.updateCounter=function(){
  63.     this.calculate();
  64.     this.formatTime();
  65.     this.countainer.innerHTML =
  66.     " <font face='digitaldreamfat' color='lime'>" + this.years + "</font> <small> <font color='white'>" + (this.years == 1? "Año" : "Años") + "</small></font>" +
  67.         " <font face='digitaldreamfat' color='lime'>" + this.months + "</font> <small> <font color='white'>" + (this.months == 1? "Mes" : "Meses") + "</small></font>" +
  68.         " <font face='digitaldreamfat' color='lime'>" + this.days + "</font> <small> <font color='white'>" + (this.days == 1? "Día" : "Días") + "</small></font>" +
  69.         " <font face='digitaldreamfat' color='lime'>" + this.hours + "</font> <small> <font color='white'>" + (this.hours == 1? "Hora" : "Horas") + "</small></font>" +
  70.         " <font face='digitaldreamfat' color='lime'>" + this.minutes + "</font> <small> <font color='white'>" + (this.minutes == 1? "Minuto" : "Minutos") + "</small></font>" +
  71.         " <font face='digitaldreamfat' color='lime'>" + this.seconds + "</font></strong> <small> <font color='white'>" + (this.seconds == 1? "Segundo" : "Segundos") + "</small></font>" +
  72.     " <font face='digitaldreamfat' color='lime'>" + this.milliseconds + "</font> <small> <font color='white'>" + "Centésimas" + "</small></font>";
  73.  
  74.     var self = this;
  75.     setTimeout(function(){self.updateCounter();}, 10);
  76. }
  77.  
  78. window.onload=function(){ new CountUp('June 2, 2011 13:30:00 GMT+0200', 'counter'); }

Quiero prescindir de los milisegundos y así poder bajar el intervalo de actualización, sin que por ello el cronómetro pierda precisión en tiempo real. El rendimiento de ciertos navegadores se ve muy afectado por este script. No lo vais a creer, pero el que mejor lo soporta es el IE
  #2 (permalink)  
Antiguo 17/08/2011, 06:27
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Décimas de segundo en un número entero

Tienes mil posibilidades: toFixed, parseInt, Math.round, etc.
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #3 (permalink)  
Antiguo 17/08/2011, 06:52
Avatar de ThunderWolf  
Fecha de Ingreso: julio-2011
Mensajes: 30
Antigüedad: 12 años, 9 meses
Puntos: 1
Respuesta: Décimas de segundo en un número entero

Soy muy novato en Javascrip, ¿podrías aclararme como y donde le implanto a ese script un toFixed() por ejemplo?
  #4 (permalink)  
Antiguo 17/08/2011, 07:06
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Décimas de segundo en un número entero

Ejemplos:
Código Javascript:
Ver original
  1. var x = 3.56;
  2. x.toFixed(); // "4"
  3. +x.toFixed(); // 4
  4. parseInt(x); // 3
  5. Math.floor(x); // 3
  6. ~~x; // 3
  7. Math.round(x); // 4
  8. Math.ceil(x); // 4
Espero que con eso te baste.
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #5 (permalink)  
Antiguo 17/08/2011, 07:12
Avatar de ThunderWolf  
Fecha de Ingreso: julio-2011
Mensajes: 30
Antigüedad: 12 años, 9 meses
Puntos: 1
Respuesta: Décimas de segundo en un número entero

Gracias, pero ya lo solucioné con this.milliseconds.toFixed() en la última función, no pensé que fuera tan fácil

Ahí te va algo de karma por las molestias.
  #6 (permalink)  
Antiguo 17/08/2011, 07:18
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Décimas de segundo en un número entero

Fíjate en que toFixed devuelve un string, ten cuidado con eso porque la coerción te puede dar problemas.
Saludos y gracias :D
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red

Etiquetas: contador, décimales, décimas, milisegundos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:22.