清除间隔不起作用

编程入门 行业动态 更新时间:2024-10-11 03:25:54
本文介绍了清除间隔不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用此代码制作幻灯片动画

iam using this code to animate a slideshow

$(document).ready(function() { /* slider initiate */ var timer = setInterval(slider,5000); }); /* slider code */ var position = 0; function slider() { $('.slider .thumbs a').removeClass('selected'); position += 660; var newPosition = position * (-1) + 'px'; if (position == 1980) { position = 0; newPosition = '0px'; } var index = position / 660; $('.slider .thumbs a').eq(index).addClass('selected'); $('.slider .slider-container').animate({left: newPosition}, 1000); } /* click animation */ $('.slider .thumbs a').click(function(){ $('.slider .thumbs a').removeClass('selected'); $(this).addClass('selected'); var index = $(this).index(); var newPosition = index * (-660) +'px'; $('.slider .slider-container').animate({left: newPosition}, 1000); clearInterval(timer); var timer = setInterval(slider,5000); });

但是当我点击拇指时,计时器只会加速,这意味着clearInterval不起作用 当我尝试将鼠标悬停清除它时,也会发生这种情况

but when i click on the thumbs the timer only accelerate that means that clearInterval doesn't work that happens too when i try to clear it on hover

推荐答案

这是范围问题.

我想您尝试清除计时器时未定义计时器(尝试使用console.log()查看).

I guess timer is undefined when you try to clear it (try to see with console.log()).

之所以加速,是因为自clearInterval为undefined的值后,您什么都不清除,并且一次运行了2个间隔.

It accelerate because since you clearInterval on undefined value you clear nothing, and you have 2 interval running at once.

在$(document).ready范围之外定义您的第一个timer变量.

Define your first timer var outside the $(document).ready scope.

var timer; $(document).ready(function() { /* slider initiate */ timer = setInterval(slider,5000); });

此外,请勿在slider函数内重新定义var timer.只需重新使用您之前声明的内容即可.

Also, don't re-define var timer inside the slider func. Just re-use the one you declared before.

但首先,请勿在slide中重复使用setInterval.您在另一个间隔内启动一个间隔.如果需要再次设置,请使用setTimeout.

But before all, don't re-use setInterval inside slide. You launch an interval within an other interval. You should use setTimeout if you need to set it again.

结论

这就足够了.使用setTimeout,您无需取消它,因为它仅触发一次.在需要时设置另一个超时,它将模拟setInterval而不需要取消它.

This is enough. With setTimeout you don't need to cancel it since it trigger only once. Set another timeout while you need to and it will simulate a setInterval without the need of canceling it.

$(document).ready(function() { /* slider initiate */ setTimeout(slider,5000); }); function slider() { // your code setTimeout(slider, 5000); }

更多推荐

清除间隔不起作用

本文发布于:2023-10-26 07:02:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:间隔   不起作用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!