validar validacion vacios llamar funcion formularios formulario evento enviar ejemplos con carga campos asincrona antes javascript load setinterval

validacion - validar formulario javascript html5



Cálculo del tiempo de carga de la página en JavaScript (3)

Estoy tratando de hacer una página web que, cuando comienza a cargar, usa un intervalo para iniciar un temporizador.

Cuando la página se carga completamente, detiene el temporizador,

pero el 99% del tiempo obtengo mediciones de tiempo de 0.00 o 0.01 incluso si lleva más tiempo.

Ocasionalmente, dice algo que tiene más sentido, como .28 o 3.10 en algún momento.

Aquí está el código si ayuda:

var hundredthstimer = 0; var secondplace = 0; function addinc(){ hundredthstimer += 1; if (inctimer == 100){ hundredthstimer = 0; secondplace += 1; } } var clockint = setInterval(addinc, 10); function init(){ var bconv1 = document.getElementById("bconverter1"); var bconv2 = document.getElementById("bconverter2"); $(bconv2).hide(); clearInterval(clockint); if (inctimer.len !== 2){ inctimer = "0" + inctimer; } alert(secondplace + "." + inctimer); } onload = init;

Por lo tanto, básicamente crea una variable llamada centésimo que se incrementa en ''1'' cada 10 milisegundos (0,01 segundos).

Entonces, si este número llega a 1000 (1 segundo completo), una variable llamada secondplace sube en 1, ya que es la cantidad de segundos completos que se ha ejecutado.

Luego, alerta segundos lugares, un punto decimal y centésimos como el tiempo de carga total.

Pero el problema anterior con números incorrectos todavía existe. ¿Por qué?


¡Nunca use las funciones setInterval o setTimeout para medir el tiempo! No son confiables, y es muy probable que la programación de ejecución de JS durante el análisis y la visualización de documentos se retrase.

En su lugar, use el objeto Date para crear una marca de tiempo cuando la página comenzó a cargarse, y calcule la diferencia con la hora en que la página se cargó por completo:

<doctype html> <html> <head> <script type="text/javascript"> var timerStart = Date.now(); </script> <!-- do all the stuff you need to do --> </head> <body> <!-- put everything you need in here --> <script type="text/javascript"> $(document).ready(function() { console.log("Time until DOMready: ", Date.now()-timerStart); }); $(window).load(function() { console.log("Time until everything loaded: ", Date.now()-timerStart); }); </script> </body> </html>


¿Por qué tan complicado? Cuando puedes hacer:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

Si necesita más veces, consulte el objeto window.performance:

console.log(window.performance);

Le mostrará el objeto de tiempo:

connectEnd Time when server connection is finished. connectStart Time just before server connection begins. domComplete Time just before document readiness completes. domContentLoadedEventEnd Time after DOMContentLoaded event completes. domContentLoadedEventStart Time just before DOMContentLoaded starts. domInteractive Time just before readiness set to interactive. domLoading Time just before readiness set to loading. domainLookupEnd Time after domain name lookup. domainLookupStart Time just before domain name lookup. fetchStart Time when the resource starts being fetched. loadEventEnd Time when the load event is complete. loadEventStart Time just before the load event is fired. navigationStart Time after the previous document begins unload. redirectCount Number of redirects since the last non-redirect. redirectEnd Time after last redirect response ends. redirectStart Time of fetch that initiated a redirect. requestStart Time just before a server request. responseEnd Time after the end of a response or connection. responseStart Time just before the start of a response. timing Reference to a performance timing object. navigation Reference to performance navigation object. performance Reference to performance object for a window. type Type of the last non-redirect navigation event. unloadEventEnd Time after the previous document is unloaded. unloadEventStart Time just before the unload event is fired.

Soporte del navegador

Más información


La respuesta mencionada por @HaNdTriX es excelente, pero no estamos seguros si DOM está completamente cargado en el siguiente código:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

Esto funciona perfectamente cuando se usa con carga como:

window.onload = function () { var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart; console.log(''Page load time is ''+ loadTime); }

Edición 1: Se agregó algo de contexto para responder

Nota: loadTime está en milisegundos, puede dividir por 1000 para obtener segundos como lo menciona @nycynik