我如何获得这个JavaScript运行每秒?
问题描述:
对不起,我是一个noob abit我只是想知道我是如何得到这个JavaScript运行每秒?我如何获得这个JavaScript运行每秒?
源代码:
<script type="text/javascript">
$(function() {
//More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if(ID) {
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").prepend(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('no posts to display');
}
return false;
});
});
</script>
答
使用setInterval()运行一段代码每x毫秒。
您可以将每秒钟运行的代码打包到名为runFunction
的函数中。
因此,这将是:
var t=setInterval(runFunction,1000);
,并停止它,你可以运行:
clearInterval(t);
答
window.setTimeout(func,1000);
这将是在1000毫秒运行FUNC。所以在func的最后,你可以再次调用window.setTimeout进入1秒的循环。你只需要定义一个终止条件。
答
使用setInterval
:
$(function(){
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
// stuff you want to do every second
}
这里的an article上setTimeout
和setInterval
之间的差异。两者都将提供您需要的功能,他们只需要不同的实施。
答
您可以使用setInterval
:
var timer = setInterval(myFunction, 1000);
只是声明你的功能myFunction的或其它名称,然后不要将其绑定到$('.more')
的现场活动。
答
您可以使用setTimeout来运行函数/命令一次或setInterval以指定的时间间隔运行函数/命令。
var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);
//To abort the interval you can use this:
clearInterval(b);
答
使用setInterval(func, delay)运行func
每delay
毫秒。
setTimeout()
运行您的功能一次delay
毫秒后 - 它不会重复运行它。常见的策略是使用setTimeout运行代码,并在代码结束时再次调用setTimeout。
'setTimeout(runFunction,1000)'please。不要传递字符串。它不会执行代码*每一秒*(至少有一些缺失)。 – 2011-04-12 16:48:53
或[setInterval()](http://www.w3schools.com/jsref/met_win_setinterval.asp) – yoavmatchulsky 2011-04-12 16:48:58
清理:var t = setInterval(mainLoop,1000); \t \t \t $(窗口).unload(函数(){ \t \t \t \t \t \t \t clearInterval(T); \t \t \t \t的console.log(“处理器对。()); \t \t \t return“”; \t \t \t}); – hannunehg 2016-06-01 16:38:46