连续每 5 秒调用一次 Javascript 函数

发布于 2024-12-01 05:54:59 字数 254 浏览 0 评论 0原文

可能的重复:
每 60 秒调用一次函数

我想每 5 秒调用一次 Javascript 函数不断地。 我见过 setTimeOut 事件。如果我想要连续使用它会正常工作吗?

Possible Duplicate:
Calling a function every 60 seconds

I want to Call a Javascript function every 5 seconds continuously.
I have seen the setTimeOut event. Will it be working fine if I want it continuously?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

美煞众生 2024-12-08 05:54:59

您可以使用 setInterval() ,参数是相同的。

const interval = setInterval(function() {
   // method to be executed;
 }, 5000);

clearInterval(interval); // thanks @Luca D'Amico

You can use setInterval(), the arguments are the same.

const interval = setInterval(function() {
   // method to be executed;
 }, 5000);

clearInterval(interval); // thanks @Luca D'Amico
帅气尐潴 2024-12-08 05:54:59

对您的函数执行“递归”setTimeout,它将在定义的每个时间量内继续执行:

function yourFunction(){
    // do whatever you like here

    setTimeout(yourFunction, 5000);
}

yourFunction();

Do a "recursive" setTimeout of your function, and it will keep being executed every amount of time defined:

function yourFunction(){
    // do whatever you like here

    setTimeout(yourFunction, 5000);
}

yourFunction();
淡水深流 2024-12-08 05:54:59

正如最佳编码实践建议的那样,请使用setTimeout setInterval

function foo() {

    // your function code here

    setTimeout(foo, 5000);
}

foo();

请注意,这不是递归函数。该函数在结束之前不会调用自身,而是调用一个 setTimeout 函数,该函数稍后将再次调用同一函数。

As best coding practices suggests, use setTimeout instead of setInterval.

function foo() {

    // your function code here

    setTimeout(foo, 5000);
}

foo();

Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout function that will be later call the same function again.

花开雨落又逢春i 2024-12-08 05:54:59

为了将来重复执行某个操作,可以使用内置的 setInterval函数来代替 setTimeout
它具有相似的签名,因此从一个到另一个的转换很简单:

setInterval(function() {
    // do stuff
}, duration);

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);
夏雨凉 2024-12-08 05:54:59

良好的工作示例此处

/*!  MenuAutoActive
---------------------------------------------*/
(function($) {

    $.fn.NoticeBoard = function() {


        // Set a timeout
        var timeOut = setTimeout(nextNotice, 5000);

        // pause on hover
        $('.noticeboard').hover(

        function() {
            clearTimeout(timeOut);
        }, function() {
            timeOut = setTimeout(nextNotice, 5000);
        });

        // Next notice function called on timeout or click
        //set a flag that use to be an oberver to listen when the fadeIn done
        var flag = true;
        function nextNotice(event) {
            if(!flag){
                return false;
            }
            clearTimeout(timeOut);
            
            flag = false;
            timeOut = setTimeout(nextNotice, 5000);

            if ($('.noticeboard span:visible').is('.noticeboard span:last-child')) {
                $('.noticeboard span:visible').fadeOut(300);
                $('.noticeboard span:first-child').fadeIn("slow",function(){
                    flag = true;
                });
            }
            else {
                $('.noticeboard span:visible').fadeOut(300).next().fadeIn("slow",function(){
                    flag = true;
                });
            }
            return false;
        }

        $('#notice-next').click(nextNotice);
        $('#notice-prev').click(function(event) {
            
            if(!flag){
                return false;
            }
            clearTimeout(timeOut);
            
            flag = false;
            timeOut = setTimeout(nextNotice, 5000);


            if ($('.noticeboard span:visible').is('.noticeboard span:first-child')) {
                $('.noticeboard span:visible').fadeOut(300);
                $('.noticeboard span:last-child').fadeIn("slow",function(){
                    flag = true;
                });
            }
            else {
                 $('.noticeboard span:visible').fadeOut(300).prev().fadeIn("slow",function(){
                    flag = true;
                });
            }
            return false;

        });

    };

/*!  
---------------------------------------------*/

})(jQuery);

/*!  OnLoad
---------------------------------------------*/
$(document).ready(function() {

    $('.noticeboard span').hide();
    $('.noticeboard span:first').show();
    $('.noticeboard').NoticeBoard();

});
/* NOTICE BOARD */
.noticeboard { position: relative; min-height: 150px;}
.noticeboard span { display: none; position: absolute; top: 0px; left: 0px;}
.noticeboard strong { padding-right: 30px; display: block;}
#notice-next { position: absolute; top: 50px; right: 10px; z-index: 100;}
#notice-prev { position: absolute; top: 50px; right: 30px; z-index: 100;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="action-box">
    <!-- NOTICEBOARD NAV -->
    <a href="#" id="notice-prev">«</a>
    <a href="#" id="notice-next">»</a>
    <!-- /NOTICEBOARD NAV -->
    
    <span class="ge"></span>
    <div class="noticeboard" style="height: 145px;">
        
        <span style="display: block;"><strong>Boy, 14, found stabbed to death</strong><a href="http://www.bbc.co.uk/news/uk-england-14570107">A 14-year-old boy has been found stabbed to death in a park in north London.</a></span><span style="display: block;"><strong>A-level passes rise for 29th year</strong><a href="http://www.bbc.co.uk/news/education-14558490">Hundreds of thousands of teenagers are getting their A-level results amid an intense battle for university places ahead of tuition fee rises.</a></span><span style="display: none;"><strong>UK: Matter of time for Gaddafi</strong><a href="http://www.bbc.co.uk/news/uk-politics-14625484">Deputy Prime Minister Nick Clegg has said it is "only a matter of time" before Col Muammar Gaddafi is defeated.</a></span>                </div>
</div>

另外:

  • 具有漂亮的淡入/淡出动画
  • ,将在上暂停:悬停
  • 将防止运行多个操作(在开始第二个操作之前完成运行动画)
  • 将防止在选项卡中损坏(浏览器停止选项卡中的脚本)

已测试并正常工作!

Good working example here

/*!  MenuAutoActive
---------------------------------------------*/
(function($) {

    $.fn.NoticeBoard = function() {


        // Set a timeout
        var timeOut = setTimeout(nextNotice, 5000);

        // pause on hover
        $('.noticeboard').hover(

        function() {
            clearTimeout(timeOut);
        }, function() {
            timeOut = setTimeout(nextNotice, 5000);
        });

        // Next notice function called on timeout or click
        //set a flag that use to be an oberver to listen when the fadeIn done
        var flag = true;
        function nextNotice(event) {
            if(!flag){
                return false;
            }
            clearTimeout(timeOut);
            
            flag = false;
            timeOut = setTimeout(nextNotice, 5000);

            if ($('.noticeboard span:visible').is('.noticeboard span:last-child')) {
                $('.noticeboard span:visible').fadeOut(300);
                $('.noticeboard span:first-child').fadeIn("slow",function(){
                    flag = true;
                });
            }
            else {
                $('.noticeboard span:visible').fadeOut(300).next().fadeIn("slow",function(){
                    flag = true;
                });
            }
            return false;
        }

        $('#notice-next').click(nextNotice);
        $('#notice-prev').click(function(event) {
            
            if(!flag){
                return false;
            }
            clearTimeout(timeOut);
            
            flag = false;
            timeOut = setTimeout(nextNotice, 5000);


            if ($('.noticeboard span:visible').is('.noticeboard span:first-child')) {
                $('.noticeboard span:visible').fadeOut(300);
                $('.noticeboard span:last-child').fadeIn("slow",function(){
                    flag = true;
                });
            }
            else {
                 $('.noticeboard span:visible').fadeOut(300).prev().fadeIn("slow",function(){
                    flag = true;
                });
            }
            return false;

        });

    };

/*!  
---------------------------------------------*/

})(jQuery);

/*!  OnLoad
---------------------------------------------*/
$(document).ready(function() {

    $('.noticeboard span').hide();
    $('.noticeboard span:first').show();
    $('.noticeboard').NoticeBoard();

});
/* NOTICE BOARD */
.noticeboard { position: relative; min-height: 150px;}
.noticeboard span { display: none; position: absolute; top: 0px; left: 0px;}
.noticeboard strong { padding-right: 30px; display: block;}
#notice-next { position: absolute; top: 50px; right: 10px; z-index: 100;}
#notice-prev { position: absolute; top: 50px; right: 30px; z-index: 100;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="action-box">
    <!-- NOTICEBOARD NAV -->
    <a href="#" id="notice-prev">«</a>
    <a href="#" id="notice-next">»</a>
    <!-- /NOTICEBOARD NAV -->
    
    <span class="ge"></span>
    <div class="noticeboard" style="height: 145px;">
        
        <span style="display: block;"><strong>Boy, 14, found stabbed to death</strong><a href="http://www.bbc.co.uk/news/uk-england-14570107">A 14-year-old boy has been found stabbed to death in a park in north London.</a></span><span style="display: block;"><strong>A-level passes rise for 29th year</strong><a href="http://www.bbc.co.uk/news/education-14558490">Hundreds of thousands of teenagers are getting their A-level results amid an intense battle for university places ahead of tuition fee rises.</a></span><span style="display: none;"><strong>UK: Matter of time for Gaddafi</strong><a href="http://www.bbc.co.uk/news/uk-politics-14625484">Deputy Prime Minister Nick Clegg has said it is "only a matter of time" before Col Muammar Gaddafi is defeated.</a></span>                </div>
</div>

Plus:

  • has nice fade in / fade out animation
  • will pause on :hover
  • will prevent running multiple actions (finish run animation before starting second)
  • will prevent going broken when in the tab ( browser stops scripts in the tabs)

Tested and working!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文