每隔5秒做一次事情,并停止代码。 (JQuery的) [英] Do something every 5 seconds and the code to stop it. (JQuery)

查看:462
本文介绍了每隔5秒做一次事情,并停止代码。 (JQuery的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何每5秒重复一次 doSomething()功能。

How can I repeat a function doSomething() every 5 seconds.

我还需要能够使用的代码让它停止这样做。

I also need code that will make it stop doing it.

动态编码可以调整频率。

And code to on-the-fly adjust the frequency.

推荐答案

setTimeout()只会启动一次命令。在这种情况下,setInterval()是你的朋友。

setTimeout() will only launch the command once. In this case, setInterval() is your friend.

var iFrequency = 5000; // expressed in miliseconds
var myInterval = 0;

// STARTS and Resets the loop if any
function startLoop() {
    if(myInterval > 0) clearInterval(myInterval);  // stop
    myInterval = setInterval( "doSomething()", iFrequency );  // run
}

function doSomething()
{
    // (do something here)
}

来自代码......

from code...

<input type="button" onclick="iFrequency+=1000; startLoop(); return false;" 
       value="Add 1 second more to the interval" />

这篇关于每隔5秒做一次事情,并停止代码。 (JQuery的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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