关于setInterval函数的问题

时间:2011-08-09 18:30:01

标签: javascript jquery

我希望div每次显示10秒,每1分钟一次。因此,在分钟开始时,div应出现10秒钟,然后消失,然后在50秒后再次出现,然后继续。

我唯一能够弄清楚的是如何让它在10秒后消失。

$(function() {

    setInterval( function() { 
        hideMsg() 
    }, 10000);

    function hideMsg() {
        $('#header p').css('display', 'none');
    }       
});

6 个答案:

答案 0 :(得分:3)

$(function() {

    showMsg();     
});
function showMsg()
{
   $('#header p').css('display', '');
   setTimeout(hideMsg, 10000);
}
function hideMsg(){
   $('#header p').css('display', 'none');
  setTimeout(showMsg, 60000);
}

就是这样,

showMsg将显示消息结束超时将在10秒后执行hideMsg然后hideMsg将隐藏消息,超时将在1分钟内执行showMsg。

答案 1 :(得分:1)

使用setTimeout()函数

$(function() {

    setInterval( function() { 
        hideMsg() 

    }, 10000);

    function showMsg(){

    }

    function hideMsg() {
        $('#header p').css('display', 'none');
        setTimeout(function(){
              $('#header p').css('display', 'block');
        }, 50000);
    }       
});

答案 2 :(得分:1)

function show(){
    // whatever your show code is

    // hide after 10 seconds
    setTimeout(function() {
                   // whatever your hide code is
              }, 10000); 
}

// invoke show every 60 seconds - show will hide itself after 10 seconds
var handle = window.setInterval(function() { show(); }, 60000);

答案 3 :(得分:1)

var messageTimer = setTimeout(showMsg, 50000);
function showMsg() {
    $('#header p').show();
    clearTimeout(messageTimer);
    messageTimer = setTimeout(hideMsg, 10000);
}
function hideMsg(){
    $('#header p').hide();
    clearTimeout(messageTimer);
    messageTimer = setTimeout(showMsg, 50000);
}  

答案 4 :(得分:0)

这个怎么样?

   $(function() {
        var count = 0;
        setInterval( function() { 
            ++count % 6 ? $('#header p').hide() 
                        : $('#header p').show();
        }, 10000);
    });

答案 5 :(得分:0)

想要使用间隔计时器来提出原创内容:

$(document).ready(function() {
    var hideCnt = 0;    // 10 second interval cntr
    setInterval(function() {
        ++hideCnt;
        if (hideCnt >= 5) {
            $('#header p').toggle();
        }
        if (hideCnt >= 6) {
            hideCnt = 0;
        }
    }, 10000);
});

显示间隔计时器解决方案工作的小提琴:http://jsfiddle.net/jfriend00/KReau/

这是更传统的味道:

$(document).ready(function() {
    function show() {
        $('#header p').show();
        setTimeout(hide, 50000);    // hide after 50 seconds
    }
    function hide() {
        $('#header p').hide();
        setTimeout(show, 10000);  // show after 10 seconds
    }
    show();
});