Repeat code every 4 seconds

后端 未结 6 2075
遇见更好的自我
遇见更好的自我 2021-01-04 04:07

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         


        
6条回答
  •  一生所求
    2021-01-04 04:36

    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.

    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
    

提交回复
热议问题