我想每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("");
}
});
另一种可能是使用 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
使用 套餐 功能
setInterval( fn , miliseconds )
来自MDC文档。
摘要
重复调用一个函数,每次调用该函数之间有固定的时间延迟。
语法
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);
哪儿
间隔ID 是你可以传递给clearInterval()的唯一区间ID。
是唯一的区间ID,你可以传递给clearInterval()。 是你想重复调用的函数。
编码 在另一种语法中,是一串你想重复执行的代码。(不推荐使用这种语法,原因与使用eval()相同)
拖延 是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);
希望能帮到你
const milliseconds = 1000
setInterval(
() => {
// self executing repeated code below
}, milliseconds);
每2秒调用一个Javascript函数,连续20秒。
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"); }