简体   繁体   English

setInterval在Firefox中无法正常工作

[英]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. 我对我的网站无限循环使用setInterval函数,但是Firefox仅处理第一个间隔,而对于下一个间隔,Firefox的我的收藏夹图标变为加载,并且F5和“刷新”按钮不起作用。

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 . 在初始加载页面时不要分开使用document.write

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 . 删除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 在文档中添加以上html并运行此脚本

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 如果它不起作用,那么巴林Firefox :)虽然可以肯定

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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