Javascript - 可以检查间隔是否已经设置?
我有一个 div,它使用一个间隔每 5 秒弹跳一次。
当滚动到页面底部时,这个div淡出并且间隔被清除。
但是,我认为间隔被多次创建并且自身重叠存在问题。
有没有办法检查是否设置了间隔,如果设置了则清除它,如果没有则设置它?
我需要清除间隔的原因是因为jquery的反弹效果导致div即使隐藏也再次出现。
I have a div that is bouncing every 5 seconds using an interval.
When scrolling to the bottom of the page, this div fades out and the interval is cleared.
However, I think there is an issue with the interval being created multiple times and overlaps upon itself.
Is there a way to check if an interval is set, and if so clear it, and if not, to set it?
The reason I need to clear the interval is because the bounce effect of jquery causes the div to appear again even if it's hidden.
JSBIN: http://jsbin.com/ijuhok/4/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
似乎您在滚动时设置了间隔。因此,如果我向下滚动,然后再次向下滚动,则您将其设置两次。
每次设置时先清除它就可以了。
http://jsbin.com/ijuhok/6
Seems that you set the interval whenever it is scrolled. So if I scroll down, and then scroll down again you set it twice.
Just clear it before hand every time you set it and you should be ok.
http://jsbin.com/ijuhok/6
您需要覆盖现有间隔,以便可以从任何地方清除它: http://jsbin.com/ijuhok/ 5/。
您可以消除
window
的$(document).ready
因为它始终可用。You need to overwrite the existing interval so that you can clear it from everywhere: http://jsbin.com/ijuhok/5/.
You can eliminate
$(document).ready
forwindow
because it's always available.您的问题是您在本地范围内定义
ResInterval
,因为您使用了var
:删除
var
前缀,并且您的代码将按预期工作:目前,ResInterval
是fadeIn
中回调函数的本地变量。当省略var
时,间隔将分配给最接近的ResInterval
声明(使用var
)。Your issue is that you're defining
ResInterval
in a local scope, because you've usedvar
:Remove the
var
prefix, and your code will work as expected: Currently,ResInterval
is a local varibale of the callback function infadeIn
. Whenvar
is omitted, the interval will be assigned to the closestResInterval
declaration (usingvar
).我按照下面的方法做了,我的问题就解决了。当您清除计时器时,您应该将值设置为“false”。
I did this like below, My problem was solved. you should set the value like "false", when you clearTimeout the timer.