【发布时间】:2011-05-24 15:10:17
【问题描述】:
我遇到了类似于this one 的 setTimeout 问题。但是该解决方案对我没有帮助,因为我无法在我的文件中使用 php。
我的网站有一个滑块,其中包含每 8 秒移动一次的图像列表。但是,当我在浏览器中打开几个选项卡然后再次切换回来时,它就发疯了。 滑块会立即一个接一个地移动图像,没有 8 秒的延时。
我只在 Chrome 和最新的 Firefox 中看到它。
**编辑:我检查了 console.log() 并且 setTimeout 在 clearTimeout 之前和之后返回相同的数字。不知道为什么。也许这也与它有关? **
编辑 2:我添加了一个小提琴:http://jsfiddle.net/Rembrand/qHGAq/8/
代码看起来像:
spotlight: {
i: 0,
timeOutSpotlight: null,
init: function()
{
$('#spotlight .controls a').click(function(e) {
// do stuff here to count and move images
// Don't follow the link
e.preventDefault();
// Clear timeout
clearTimeout(spotlight.timeOutSpotlight);
// Some stuff here to calculate next item
// Call next spotlight in 8 seconds
spotlight.timeOutSpotlight = setTimeout(function () {
spotlight.animate(spotlight.i);
}, 8000);
});
// Select first item
$('#spotlight .controls a.next:first').trigger('click');
},
animate: function(i)
{
$('#spotlight .controls li:eq(' + (spotlight.i) + ') a.next').trigger('click');
}
}
【问题讨论】:
-
只有在您打开同一个网站的新标签页,还是打开任何个新标签页并切换回来时才会出现这种情况?
-
任何网站的随机标签。
-
多么有趣。一些额外的测试可以帮助查看发生了什么 - 在回调期间,如果您 console.log 日期时间以查看代码命中的实际间隔 - 是 8 秒吗?而且,如果您离开页面 X # 秒,您是否看到在给定的经过时间内正确的控制台日志记录事件数?
-
如果您继续为此苦苦挣扎,我建议您使用jsfiddle.net 复制它并在此处发布小提琴。
标签: javascript jquery timer settimeout