我是JavaScript / jQuery的新手,但已经制作了一个脚本来改变背景图片。
第一个脚本
第一个脚本版本工作正常,并执行以下操作:
创建一个setInterval定时器,调用函数backgroundChange()每7秒运行一次 决定下一张图片网址 设置背景图片这很有效,但问题是当网站处于活动状态时,在连接速度较慢时,背景图片不会及时加载以进行下一次计时器更改。
新脚本
所以新版本:
创建一个setTimeout计时器,调用函数backgroundChange()在7秒后运行var theTimer = setTimeout(backgroundChange, 7000);
clearsTimeout(当然我不应该运行它?)window.clearTimeout(theTimer);
决定下一张图片网址 等到图片加载完毕: 然后设置背景图片 然后添加一个新的setTimeout计时器$('#testImage').attr('src', imageText).load(function() {
$('#backgroundTop').fadeIn(timeIn,function() { theTimer = setTimeout(backgroundTimer, 7000); });});
问题是,当计时器运行并存在于.load函数中时,计时器现在似乎被调用了两倍。
我还没有故意不发布我的代码,因为我想首先确保我的理解是正确的,而不是仅修复我的代码。
非常。
I'm fairly new to JavaScript/jQuery, but have made a script to change the background picture.
First Script
The first script version works fine and does the following:
creates a setInterval timer that calls function backgroundChange() to run every 7 seconds decides the next picture URL sets the background pictureThis works great, but the problem is when the website is live, on a slow connection the background picture doesn't load in time for the next timer change.
New Script
So the new version:
creates a setTimeout timer that calls function backgroundChange() to run after 7 secondsvar theTimer = setTimeout(backgroundChange, 7000);
clearsTimeout (surely I shouldn't have to run this?)window.clearTimeout(theTimer);
decides the next picture URL waits until the picture is loaded: then sets the background picture then adds a new setTimeout timer$('#testImage').attr('src', imageText).load(function() {
$('#backgroundTop').fadeIn(timeIn,function() { theTimer = setTimeout(backgroundTimer, 7000); });});
The problem is that the timer now seems to be called double the amount of times whenever the timer runs and exists in the .load function.
I havent purposely not posted my code yet, as I want to make sure my understanding is correct first, rather than someone just fixing my code.
Ta very much.
最满意答案
在添加下一个加载处理程序之前,需要取消绑定加载处理程序,因为它们会随着代码的存在而不断堆积。 每次迭代,您都会添加一个额外的处理程序来执行完全相同的操作。 在重新附加之前使用unbind删除旧处理程序:
$('#testImage').unbind('load');You need to unbind the load handler before you add the next one, since they keep piling up as your code stands. With every iteration, you add an extra handler that does the exact same thing. Use unbind to remove the old handler before you reattach:
$('#testImage').unbind('load');更多推荐
发布评论