Ric*_*nop 227 javascript function timer setinterval
使用setTimeout()它可以在指定的时间启动一个功能:
setTimeout(function, 60000);
Run Code Online (Sandbox Code Playgroud)
但是,如果我想多次启动该功能怎么办?每次时间间隔过去,我都想执行该功能(每60秒,让我们说).
jAn*_*ndy 351
如果您不在乎代码中的代码是否timer需要超过您的间隔,请使用setInterval():
setInterval(function, delay)
Run Code Online (Sandbox Code Playgroud)
这会反复激活作为第一个参数传入的函数.
更好的方法是setTimeout与self-executing anonymous功能一起使用:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
Run Code Online (Sandbox Code Playgroud)
这保证了在代码执行之前没有进行下一次调用.我arguments.callee在这个例子中用作函数引用.这是一个更好的方法,为函数命名并调用它,setTimeout因为arguments.callee在ecmascript 5中已弃用.
Blu*_*ird 64
使用
setInterval(function, 60000);
Run Code Online (Sandbox Code Playgroud)
编辑:(如果你想在启动后停止时钟)
脚本部分
<script>
var int=self.setInterval(function, 60000);
</script>
Run Code Online (Sandbox Code Playgroud)
和HTML代码
<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>
Run Code Online (Sandbox Code Playgroud)
Om *_*kar 25
更好地利用jAndy的答案来实现轮询函数,该函数每秒轮询一次interval,并在timeout几秒钟后结束.
function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000;
(function p() {
fn();
if (((new Date).getTime() - startTime ) <= timeout) {
setTimeout(p, interval);
}
})();
}
pollFunc(sendHeartBeat, 60000, 1000);
Run Code Online (Sandbox Code Playgroud)
UPDATE
根据评论,更新它以传递函数停止轮询的能力:
function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000,
canPoll = true;
(function p() {
canPoll = ((new Date).getTime() - startTime ) <= timeout;
if (!fn() && canPoll) { // ensures the function exucutes
setTimeout(p, interval);
}
})();
}
pollFunc(sendHeartBeat, 60000, 1000);
function sendHeartBeat(params) {
...
...
if (receivedData) {
// no need to execute further
return true; // or false, change the IIFE inside condition accordingly.
}
}
Run Code Online (Sandbox Code Playgroud)
Opt*_*ive 14
在jQuery中你可以这样做.
function random_no(){
var ran=Math.random();
jQuery('#random_no_container').html(ran);
}
window.setInterval(function(){
/// call your function here
random_no();
}, 6000); // Change Interval here to test. For eg: 5000 for 5 secRun Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="random_no_container">
Hello. Here you can see random numbers after every 6 sec
</div>Run Code Online (Sandbox Code Playgroud)
您可以在函数末尾调用setTimeout.这会将它再次添加到事件队列中.您可以使用任何类型的逻辑来改变延迟值.例如,
function multiStep() {
// do some work here
blah_blah_whatever();
var newtime = 60000;
if (!requestStop) {
setTimeout(multiStep, newtime);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
订阅 asetInterval()并使用 aclearInterval()停止永远循环的一个很好的例子:
function myTimer() {
}
var timer = setInterval(myTimer, 5000);
Run Code Online (Sandbox Code Playgroud)
调用此行来停止循环:
clearInterval(timer);
Run Code Online (Sandbox Code Playgroud)