Cleartimeout()

时间:2013-10-04 12:35:04

标签: javascript

我有一个视频列表,如果用户点击一个视频然后在第一个视频完成之前点击第二个视频,则计时器会继续,第二个视频会在不应该的时候更改。我已经尝试使用clearTimeout来停止第一个视频计时器,但它没有做任何事情。

  var last_div = 0;
  function getVid(div_num, vid_length, count, id)
  {
  clearTimeout(timer1)
  time_limit = vid_length * 1000 + 4000;  //plus 4000 is to account for the lagging of the youtube video loading

    if(last_div == 0)
    {
      last_div = div_num;
      document.getElementById("vid_div" + div_num).style.background="#DCE4EB";
    }
    else
    {
      document.getElementById("vid_div" + last_div).style.background="";
      last_div = div_num;
      document.getElementById("vid_div" + div_num).style.background="#DCE4EB";
    }

    player.loadVideoById(id);
    player.setVolume(20);

    if(div_num != count)
    {
    div_num++;

      var timer1 = setTimeout(function(){
        document.getElementById("vid_div" + div_num).onclick();
      },
      time_limit);
    }
    else
    {
      setTimeout(function(){
        document.getElementById("vid_div" + div_num).style.background="";
      },
      time_limit);
    }
  }

2 个答案:

答案 0 :(得分:1)

var timer1是一个局部变量。那是你的一个问题。另一个问题是另一个setTimeout没有变量。

答案 1 :(得分:0)

将其更改为:

 var last_div = 0,timer1;
  function getVid(div_num, vid_length, count, id)
  {
  clearTimeout(timer1)
  time_limit = vid_length * 1000 + 4000;  //plus 4000 is to account for the lagging of the youtube video loading

    if(last_div == 0)
    {
      last_div = div_num;
      document.getElementById("vid_div" + div_num).style.background="#DCE4EB";
    }
    else
    {
      document.getElementById("vid_div" + last_div).style.background="";
      last_div = div_num;
      document.getElementById("vid_div" + div_num).style.background="#DCE4EB";
    }

    player.loadVideoById(id);
    player.setVolume(20);

    if(div_num != count)
    {
    div_num++;

      timer1 = setTimeout(function(){
        document.getElementById("vid_div" + div_num).onclick();
      },
      time_limit);
    }
    else
    {
      timer1 = setTimeout(function(){
        document.getElementById("vid_div" + div_num).style.background="";
      },
      time_limit);
    }
  }