每4秒重复一次代码

Repeat code every 4 seconds

本文关键字:一次 代码 4秒      更新时间:2023-09-26

我想每4秒重复一次这段代码,如何使用javascript或jquery?谢谢。:)

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

使用setInterval函数

setInterval( fn , miliseconds )

来自MDC文档:

摘要

重复调用一个函数,每次调用该函数之间有固定的时间延迟。

语法

var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);

其中

intervalID是一个可以传递给clearInterval()的唯一间隔ID。

func是要重复调用的函数。

code在替代语法中,是要重复执行的代码字符串。(不建议使用此语法,原因与使用eval()相同)

delay是setInterval()函数在每次调用func之前应等待的毫秒数(千分之一秒)。与setTimeout一样,有一个强制的最小延迟。

请注意,以第一种语法向函数传递附加参数在Internet Explorer中不起作用。

示例

// alerts "Hey" every second
setInterval(function() { alert("Hey"); }, 1000);
setInterval(function(){
  // your code...
}, 4000);

这在javascript中并不太难。

// declare your variable for the setInterval so that you can clear it later
var myInterval; 
// set your interval
myInterval = setInterval(whichFunction,4000);
whichFunction{
    // function code goes here
}
// this code clears your interval (myInterval)
window.clearInterval(myInterval); 

希望这能有所帮助!

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

这将确保请求之间至少间隔4秒,因为在收到上一个响应之前,下一个请求不会开始。

 // 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
const milliseconds = 4000 
setInterval(
  () => { 
  // self executing repeated code below
}, milliseconds);

连续20秒,每2秒调用一个Javascript函数。

var intervalPromise;
$scope.startTimer = function(fn, delay, timeoutTime) {
    intervalPromise = $interval(function() {
        fn();
        var currentTime = new Date().getTime() - $scope.startTime;
        if (currentTime > timeoutTime){
            $interval.cancel(intervalPromise);
          }                  
    }, delay);
};
$scope.startTimer(hello, 2000, 10000);
hello(){
  console.log("hello");
}