function timeClock() { setTimeout("timeClock()", 1000); now = new Date(); alert(now); f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes()); return f_date; } <span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>alerta (ahora); me da el valor cada segundo pero no se actualiza en el html. ¿Cómo puedo actualizar la hora en el html sin actualizar la página?
Hay una serie de errores en su código. Sin el uso de var delante de sus declaraciones de variables, las filtra al alcance global.
Además, se desaconseja el uso de document.write .
Así es como lo haría:
JavaScript:
function updateClock() { var now = new Date(), // current date months = ['January', 'February', '...']; // you get the idea time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea // a cleaner way than string concatenation date = [now.getDate(), months[now.getMonth()], now.getFullYear()].join(' '); // set the content of the element with the ID time to the formatted string document.getElementById('time').innerHTML = [date, time].join(' / '); // call this function again in 1000ms setTimeout(updateClock, 1000); } updateClock(); // initial callHTML:
<div id="time"> </div>setInterval(expresión, tiempo de espera);
La función setTimeout está diseñada para un solo tiempo de espera, por lo que usar setInterval sería una opción más apropiada. SetInterval se ejecutará regularmente sin las líneas adicionales que tiene la respuesta de Ivo.
Reescribiría la respuesta de Ivo de la siguiente manera:
JavaScript:
function updateClock() { // Ivo's content to create the date. document.getElementById('time').innerHTML = [date, time].join(' / ') } setInterval(updateClock, 1000);¡Pruébelo usted mismo! https://jsfiddle.net/avotre/rtuna4x7/2/
Formato/actualización de tiempo de Javascript directo
1: crear función de conversión de mes 2: crear función de tiempo 3: crear función de actualización 4: crear función de salida
// month converter from index / 0-11 values function covertMonth(num){ let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; // look into index with num 0-11 let computedRes = months[num]; return computedRes; } // time func function Time(){ // important to get new instant of the Date referrance let date = new Date(); this.time = date.toLocaleTimeString(); this.year = date.getUTCFullYear(); this.day = date.getUTCDate(); this.month = date.getUTCMonth(); this.currentTime = date.toLocaleTimeString() + ' ' + covertMonth(this.month) + ' ' + this.day + ' ' + this.year; return this.currentTime; } function timeOutPut(){ let where = document.getElementById('some-id'); where.textContent = Time(); // 1:21:39 AM Dec 17 2017 } // run every 5secs setInterval(timeOutPut, 5000);