[英]trying to make a timer stop when the user reaches the bottom of the page using jQuery
我有一个计时器,在页面加载时开始计时。 我希望它在用户滚动到页面底部时停止。 这是我编写的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)
块。
有人可以告诉我我在做什么错吗?
编辑:我做了一个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
}
});
});
确定页面底部,您可以尝试此操作
if(window.innerHeight + document.body.scrollTop >= document.body.offsetHeight) {
stop = true;
}
更新:
您需要使变量全局stop
,并在documnet.ready
函数外部声明它。
setInterval
函数返回数字,您以后可以将其传递给clearInterval
以停止计时器。
宣布
var Timeout=0;
校验
if(stop == false)
在setInterval函数中
喜欢
Timeout=setInterval(function ()
{
if(stop == false)
{
time += 1;
var displayTime = time/10;
if(displayTime % 1 != 0)
{
$('.time').text(displayTime.toString());
}
else
{
$('.time').text(displayTime.toString() + ".0");
}
}
else
{
clearInterval(Timeout);
}
}, 100);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.