JavaScript setTimeout()重复项 [英] JavaScript setTimeout() duplicates

查看:242
本文介绍了JavaScript setTimeout()重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触JavaScript/jQuery,但是编写了脚本来更改背景图片.

I'm fairly new to JavaScript/jQuery, but have made a script to change the background picture.

第一个脚本

第一个脚本版本可以正常工作,并且可以执行以下操作:

The first script version works fine and does the following:

  • 创建一个setInterval计时器,该计时器调用函数backgroundChange()以每7秒运行一次
  • 确定下一张图片的网址
  • 设置背景图片

这很好用,但是问题是当网站处于活动状态时,如果连接速度较慢,背景图片将无法在下次计时器更改时及时加载.

This 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.

新脚本

所以新版本:

  • 创建一个setTimeout计时器,该计时器调用函数backgroundChange()在7秒后运行

var theTimer = setTimeout(backgroundChange, 7000);

  • clearsTimeout(确定我不必运行此命令吗?)

window.clearTimeout(theTimer);

  • 确定下一张图片的网址
  • 等待图片加载完毕
  • 然后设置背景图片
  • 然后添加一个新的setTimeout计时器

$('#testImage').attr('src', imageText).load(function() {

$('#testImage').attr('src', imageText).load(function() {

    $('#backgroundTop').fadeIn(timeIn,function() 
    {
         theTimer = setTimeout(backgroundTimer, 7000);
    });

});

问题在于,计时器现在每次运行并存在于.load函数中时,其调用次数似乎是原来的两倍.

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.

非常多.

推荐答案

在添加下一个加载处理程序之前,您需要取消绑定该加载处理程序,因为它们会随着您的代码而不断堆积.在每次迭代中,您都会添加一个额外的处理程序,该处理程序执行完全相同的操作.重新连接之前,请使用unbind删除旧的处理程序:

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');

这篇关于JavaScript setTimeout()重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆