Jquery自调用函数循环
我试图检查我的自调用 jquery 函数是否完成了工作,但发生的情况是结果在每次自调用时不断相乘。
HTML
<span id="checkit"></span>
Javascript
$(function(){
callme();
});
function callme(){
$('#checkit').append("callme loaded<br />");
setInterval("callme()", 5000);
}
通常,这是我的代码结果。
加载。
callme loaded
5 秒后,
callme loaded <from previous
callme loaded
再过 5 秒
callme loaded <from previous
callme loaded <from previous
callme loaded
callme loaded
callme loaded
callme loaded
抱歉,我的解释很蹩脚。我一直在认真思考为什么会发生这些事情。如果有人可以解释我做错了什么,或者解决方案。请帮助 - 这个问题困扰了我好几天。
I'm trying to check whether my self-calling jquery function did the job done but what happened is that the result keep multiplying on each self calling.
HTML
<span id="checkit"></span>
Javascript
$(function(){
callme();
});
function callme(){
$('#checkit').append("callme loaded<br />");
setInterval("callme()", 5000);
}
Normally, here's my result for the codes.
onLoad.
callme loaded
5 seconds later
callme loaded <from previous
callme loaded
another 5 seconds later
callme loaded <from previous
callme loaded <from previous
callme loaded
callme loaded
callme loaded
callme loaded
Sorry for the crappy explanation. I've been thinking really hard why this stuffs happened. If anyone could explain what I did wrong, or the solution for this. Please help - This problem kept bugging me for days.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每次调用
callme
时,您都会创建一个新的间隔,该间隔将再次调用callme
。您可以使用clearInterval
清除之前的间隔,或使用setTimeout
代替setInterval
。Each time you call
callme
, you are creating a new interval that will callcallme
again. You can clear the previous interval usingclearInterval
or usesetTimeout
instead ofsetInterval
.setInterval 不是 setTimeout。您没有清除间隔,因此它们正在复利。
setInterval is not setTimeout. You are not clearing the interval, so they are compounding.
您需要检查#checkit 元素是否已创建。并且,您需要使用超时(仅调用一次)而不是间隔(持续不断):
学习参考:
You need to check if the #checkit element has been created. And, you need to use a timeout (which only calls once) instead of an interval (which goes on and on):
Reference for learning: window.setTimeout