Date() object does not work in Mozilla Firefox

Asked

Viewed 69 times

1

My Javascript code has a Date object, however this script only works in Chrome and IE, and in Firefox nothing appears, because it happens?

Code:

function relogio(elemento){
			
	var target = document.querySelector(elemento);				
	var rel = new Date();
	var hora 		= rel.getHours();
	var minuto 		= rel.getMinutes();
	var segundo 	= rel.getSeconds();
				
	if(hora < 10){
		hora = "0"+hora;
	}
	if(minuto < 10){
		minuto = "0"+minuto;
	}
	if(segundo < 10){
		segundo = "0"+segundo;
	}
	target.innerText = hora+":"+minuto+":"+segundo;
}
window.setInterval("relogio('#relogio')", 1000);
<div id="relogio">
		
</div>

Also available on jsfiddle.

Please submit only Javascript solutions.

1 answer

2


The reason your code does not work on jsFiddle is because this function relogio is being declared within the onload jsFiddle, and therefore not available in the global scope where the eval of setInterval run. There is another question with a similar problem here: /a/35268/129

Correcting that would make it so: https://jsfiddle.net/qkssh4s1/5/

Suggestion of improvement:

function relogio(id) {
    var target = document.querySelector(id);
    function pad(nr) {
        return nr < 10 ? '0' + nr : nr;
    }
    return function() {
        var rel = new Date();
        var hora = rel.getHours();
        var minuto = rel.getMinutes();
        var segundo = rel.getSeconds();
        target.innerText = [hora, minuto, segundo].map(pad).join(':');
    }
}
window.setInterval(relogio('#relogio'), 1000);

jsFiddle: https://jsfiddle.net/qkssh4s1/4/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.