简体   繁体   中英

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);

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; 

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>
<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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM