BlackMB
BlackMB

Reputation: 228

setInterval doesn't work correctly in firefox

i use setInterval function for my website infinite loop, but Firefox only handles the first interval and for next one, the fav icon of my site changes to loading, and F5 and refresh button don't work.

function printTime()
{
    var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
    document.write(hours + ":" + mins + ":" + sec);
}

setInterval("printTime()", 1000);

Upvotes: 0

Views: 2788

Answers (4)

Mr.G
Mr.G

Reputation: 3569

Try this simple example:

function printTime()
{
    var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
    var div = document.getElementById('divID').innerHTML = hours + ":" + mins + ":" + sec;

}

setInterval(printTime(), 1000);

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

Remove document.write. try something like this

$(document).ready(function () {
    function printTime() {
        var now = new Date();
        var hours = now.getHours();
        var mins = now.getMinutes();
        var sec = now.getSeconds();
        $("#myDiv").html(hours + ":" + mins + ":" + sec);
    }

    setInterval(printTime, 1000);
});
<div id="myDiv"></div>

Upvotes: 1

K D
K D

Reputation: 5989

<div id="test">Hello</div>

add above html in your document and run this script

var flag = false;
function printTime()
{
    var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
//    document.write(hours + ":" + mins + ":" + sec);
 if(flag==true)
 {
    document.getElementById("test").backgroundColor="green";
    flag = false;
 }else
 {
    document.getElementById("test").backgroundColor="red";
    flag = true;
 }

}

setInterval("printTime()", 1000);

if it doesn't work then balim Firefox :) although it will work surely

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

That's totally expected. Don't use document.write apart during the initial loading of the page.

Create an element and append it to the body instead.

For example :

function printTime(){
    var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var sec = now.getSeconds();
    var txt = document.createTextNode(hours + ":" + mins + ":" + sec);
    document.body.appendChild(txt); 
}
setInterval(printTime, 1000); // note also the difference here : don't eval

Note that after a few hours, your page will be a little long. If you wanted to change an element instead of appending, you'd do

document.getElementById('someId').innerHTML = hours + ":" + mins + ":" + sec; 

Upvotes: 11

Related Questions