Object Date () does not work in Mozilla Firefox

1

My Javascript code has a Date object, however this script only works in Chrome and IE, and in Firefox nothing appears, why does this happen?

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.

    
asked by anonymous 30.10.2016 / 09:13

1 answer

2

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

Correcting this would look like this: link

Suggestion for 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: link

    
30.10.2016 / 09:23