Foros del Web » Programando para Internet » Javascript »

Cuenta regresiva con hora del servidor

Estas en el tema de Cuenta regresiva con hora del servidor en el foro de Javascript en Foros del Web. Hola, mi problema es el siguiete: tengo una web donde hay cuenta regresiva de productos. El problema es que el tiempo restante depende del la ...
  #1 (permalink)  
Antiguo 31/03/2013, 20:56
 
Fecha de Ingreso: marzo-2013
Mensajes: 1
Antigüedad: 11 años
Puntos: 0
Pregunta Cuenta regresiva con hora del servidor

Hola, mi problema es el siguiete: tengo una web donde hay cuenta regresiva de productos. El problema es que el tiempo restante depende del la hora del cliente ya que se hace en javascript.

La solucion seria poner el javascript con la hora del servidor por medio de php o de alguna otra forma. aca dejo el script usado:

intente cambiar la parte donde obtiene la hora actual, pero sin exito.
Especificamente esta linea: currentDate = Math.floor($.now() / 1000);


<script>
(function($) {
$.fn.countdown = function(options, callback) {

//custom 'this' selector
thisEl = $(this);

//array of custom settings
var settings = {
'date': null,
'date2': null,
'format': null
};

//append the settings array to options
if(options) {
$.extend(settings, options);
}

//main countdown function
function countdown_proc() {

eventDate = Date.parse(settings['date']) / 1000;

currentDate = Math.floor($.now() / 1000);


if(eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}

seconds = eventDate - currentDate;

days = Math.floor(seconds / (60 * 60 * 24)); //calculate the number of days
seconds -= days * 60 * 60 * 24; //update the seconds variable with no. of days removed

hours = Math.floor(seconds / (60 * 60));
seconds -= hours * 60 * 60; //update the seconds variable with no. of hours removed

minutes = Math.floor(seconds / 60);
seconds -= minutes * 60; //update the seconds variable with no. of minutes removed

//conditional Ss
if (days == 1) { thisEl.find(".timeRefDays").text("day"); } else { thisEl.find(".timeRefDays").text("days"); }
if (hours == 1) { thisEl.find(".timeRefHours").text("hour"); } else { thisEl.find(".timeRefHours").text("hours"); }
if (minutes == 1) { thisEl.find(".timeRefMinutes").text("minute"); } else { thisEl.find(".timeRefMinutes").text("minutes"); }
if (seconds == 1) { thisEl.find(".timeRefSeconds").text("second"); } else { thisEl.find(".timeRefSeconds").text("seconds"); }

//logic for the two_digits ON setting
if(settings['format'] == "on") {
days = (String(days).length >= 2) ? days : "0" + days;
hours = (String(hours).length >= 2) ? hours : "0" + hours;
minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;
seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;
}

//update the countdown's html values.
if(!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds);
} else {
alert("Invalid date. Here's an example: 12 Tuesday 2012 17:30:00");
clearInterval(interval);
}
}

//run the function
countdown_proc();

//loop the function
interval = setInterval(countdown_proc, 1000);

}
}) (jQuery);
</script>
<script>


$("#countdown").countdown({
//date: "17 august 2013 12:00:00",

date: "<?php echo date("d F Y",strtotime($fecha_finaliza)); ?> <?php echo $reg["hora_finaliza"] ?> ",
format: "on"
},

function() {
// callback function

});




</script>

saludos y gracias por tomarse su tiempo!
  #2 (permalink)  
Antiguo 01/04/2013, 11:42
Avatar de maycolalvarez
Colaborador
 
Fecha de Ingreso: julio-2008
Ubicación: Caracas
Mensajes: 12.120
Antigüedad: 15 años, 9 meses
Puntos: 1532
Respuesta: Cuenta regresiva con hora del servidor

por favor utilice el highlight para mostrar código.

Ten en cuenta que el verdadero problema es el polling que genera estar consultando (enviando peticiones http) al servidor, eso puede suturarlo cuando se incremente la cantidad de usuarios, causándote un enorme cuello de botella.

la solución es tratar de crear una conexión persistente con el servidor, lo cual no es nada simple, tienes opciones como HTML5 WebSockets pero depende de ambas partes el poder implementarlo (navegador/servidor), SSE (no funciona en IE), entre otras.

No te recomiendo Ajax Longpolling, porque no te va a servir si quieres la hora en tiempo real, la alternativa más viable es sincronizar cada cierto tiempo con el servidor y llevar la cuenta localmente en JS, y que en determinada acción, como click en compra del producto actualice el contador, validando desde el lado del servidor.
__________________
¡Por favor!: usa el highlight para mostrar código
El que busca, encuentra...
  #3 (permalink)  
Antiguo 01/04/2013, 12:38
Avatar de marlanga  
Fecha de Ingreso: enero-2011
Ubicación: Murcia
Mensajes: 1.024
Antigüedad: 13 años, 3 meses
Puntos: 206
Respuesta: Cuenta regresiva con hora del servidor

Código Javascript:
Ver original
  1. (function($) {
  2.                 $.fn.countdown = function(options, callback) {
  3.                    
  4.                     //custom 'this' selector
  5.                     thisEl = $(this);
  6.                    
  7.                     var last=$.now();
  8.                     var acumulated=0;
  9.                    
  10.                     //array of custom settings
  11.                     var settings = {
  12.                         'date': null,
  13.                         'date2': null,
  14.                         'format': null
  15.                     };
  16.                    
  17.                     //append the settings array to options
  18.                     if(options) {
  19.                         $.extend(settings, options);
  20.                     }
  21.                    
  22.                     //main countdown function
  23.                     function countdown_proc() {
  24.                        
  25.                         eventDate = Date.parse(settings['date']);
  26.                        
  27.                         if (settings['date2'])
  28.                         {
  29.                             acumulated+= $.now() - last;
  30.                             currentDate = Date.parse(settings['date2'])+acumulated;
  31.                             last=$.now();
  32.                         }
  33.                         else
  34.                         {
  35.                             currentDate = Math.floor($.now());
  36.                         }
  37.                        
  38.                        
  39.                         if(eventDate <= currentDate) {
  40.                             callback.call(this);
  41.                             clearInterval(interval);
  42.                         }
  43.                        
  44.                         seconds = Math.floor((eventDate - currentDate)/1000);
  45.                        
  46.                         days = Math.floor(seconds / (60 * 60 * 24)); //calculate the number of days
  47.                         seconds -= days * 60 * 60 * 24; //update the seconds variable with no. of days removed
  48.                        
  49.                         hours = Math.floor(seconds / (60 * 60));
  50.                         seconds -= hours * 60 * 60; //update the seconds variable with no. of hours removed
  51.                        
  52.                         minutes = Math.floor(seconds / 60);
  53.                         seconds -= minutes * 60; //update the seconds variable with no. of minutes removed
  54.                        
  55.                         //conditional Ss
  56.                         if (days == 1) { thisEl.find(".timeRefDays").text("day"); } else { thisEl.find(".timeRefDays").text("days"); }
  57.                         if (hours == 1) { thisEl.find(".timeRefHours").text("hour"); } else { thisEl.find(".timeRefHours").text("hours"); }
  58.                         if (minutes == 1) { thisEl.find(".timeRefMinutes").text("minute"); } else { thisEl.find(".timeRefMinutes").text("minutes"); }
  59.                         if (seconds == 1) { thisEl.find(".timeRefSeconds").text("second"); } else { thisEl.find(".timeRefSeconds").text("seconds"); }
  60.                        
  61.                         //logic for the two_digits ON setting
  62.                         if(settings['format'] == "on") {
  63.                             days = (String(days).length >= 2) ? days : "0" + days;
  64.                             hours = (String(hours).length >= 2) ? hours : "0" + hours;
  65.                             minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;
  66.                             seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;
  67.                         }
  68.                        
  69.                         //update the countdown's html values.
  70.                         if(!isNaN(eventDate) || !isNaN(currentDate)) {
  71.                             thisEl.find(".days").text(days);
  72.                             thisEl.find(".hours").text(hours);
  73.                             thisEl.find(".minutes").text(minutes);
  74.                             thisEl.find(".seconds").text(seconds);
  75.                         } else {
  76.                             alert("Invalid date. Here's an example: 12 Tuesday 2012 17:30:00");
  77.                             clearInterval(interval);
  78.                         }
  79.                     }
  80.                    
  81.                     //run the function
  82.                     countdown_proc();
  83.                    
  84.                     //loop the function
  85.                     interval = setInterval(countdown_proc, 1000);
  86.                    
  87.                 }
  88.             }) (jQuery);
  89.             $(function(){
  90.            
  91.                 $("#countdown").countdown({
  92.                 //date: "17 august 2013 13:00:00",
  93.                 //date2: "17 august 2013 12:00:00",
  94.                 date: "<?php echo date("d F Y",strtotime($fecha_finaliza)); ?> <?php echo $reg["hora_finaliza"] ?> ",
  95.                 date2: "<?php echo date("d F Y",strtotime($fecha_actual)); ?> <?php echo $reg["hora_actual"] ?> ",
  96.                 format: "on"
  97.                 },
  98.  
  99.                 function() {
  100.                 // callback function
  101.  
  102.                 });
  103.             });

Etiquetas: html, jquery, php, regresiva, select, servidor
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 23:47.