每4秒钟重复一次代码 [英] Repeat code every 4 seconds

查看:44
本文介绍了每4秒钟重复一次代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每4秒钟重复一次此代码,我该如何轻松地使用javascript或jquery呢?谢谢.:)

I want repeat this code every 4 seconds, how i can do it with javascript or jquery easly ? Thanks. :)

$.get("request2.php", function(vystup){
   if (vystup !== ""){
      $("#prompt").html(vystup);
      $("#prompt").animate({"top": "+=25px"}, 500).delay(2000).animate({"top": "-=25px"}, 500).delay(500).html("");
    }
});

推荐答案

另一种可能性是使用 setTimeout ,但是将其与您的代码一起放置在一个函数中,该函数在递归调用中回调 $.get()请求.

Another possibility is to use setTimeout, but place it along with your code in a function that gets called recursively in the callback to the $.get() request.

这将确保请求的间隔为 minimum (最小),间隔为4秒,因为下一个请求要等到收到上一个响应后才开始.

This will ensure that the requests are a minimum of 4 seconds apart since the next request will not begin until the previous response was received.

 // v--------place your code in a function
function get_request() {
    $.get("request2.php", function(vystup){
       if (vystup !== ""){
          $("#prompt").html(vystup)
                      .animate({"top": "+=25px"}, 500)
                      .delay(2000)
                      .animate({"top": "-=25px"}, 500)
                      .delay(500)
                      .html("");
        }
        setTimeout( get_request, 4000 ); // <-- when you ge a response, call it
                                         //        again after a 4 second delay
    });
}

get_request();  // <-- start it off

这篇关于每4秒钟重复一次代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆