我有一个计时器,在页面加载时开始计时。我希望它在用户滚动到页面底部时停止。这是我编写的 jQuery:
function timerTick(time, stop)
{
if(stop == false)
{
setInterval(function ()
{
time += 1;
var displayTime = time/10;
if(displayTime % 1 != 0)
{
$('.time').text(displayTime.toString());
}
else
{
$('.time').text(displayTime.toString() + ".0");
}
}, 100);
}
else //behavior is the same if i remove the else block
{
return;
}
}
$(document).ready(function () {
var time = 0;
var stop = false;
timerTick(time, stop);
//check if we're at the bottom
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
stop = true;
}
});
});
计时器计时得很完美,问题是我无法让它停止。如果我将 stop = true;
行替换为 alert('abc');
,则当用户到达底部时会显示警报。所以所有的部分都在工作,只是出于某种原因将 stop 设置为 true 并不能阻止 timerTick 函数进入 if(stop == false)
block 。
有人可以告诉我我做错了什么吗?
<小时/>编辑:我做了一个 jsFiddle .
最佳答案
当用户到达页面末尾时,您必须清除间隔。否则它将继续执行。
尝试:
var intervalId;
function timerTick(time, stop)
{
if(stop == false)
{
intervalId=setInterval(function () //Set the interval in a var
{
time += 1;
var displayTime = time/10;
if(displayTime % 1 != 0)
{
$('.time').text(displayTime.toString());
}
else
{
$('.time').text(displayTime.toString() + ".0");
}
}, 100);
}
else //behavior is the same if i remove the else block
{
return;
}
}
$(document).ready(function () {
var time = 0;
var stop = false;
timerTick(time, stop);
//check if we're at the bottom
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
stop = true;
clearInterval(intervalId);//HERE clear the interval
}
});
});
关于javascript - 尝试使用 jQuery 在用户到达页面底部时停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24575725/