gpt4 book ai didi

javascript - 尝试使用 jQuery 在用户到达页面底部时停止计时器

转载 作者:行者123 更新时间:2023-11-28 01:09:58 25 4
gpt4 key购买 nike

我有一个计时器,在页面加载时开始计时。我希望它在用户滚动到页面底部时停止。这是我编写的 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
}
});


});

DEMO

关于javascript - 尝试使用 jQuery 在用户到达页面底部时停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24575725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com