如何不增加setInterval然后多次调用

时间:2015-12-16 13:06:07

标签: javascript jquery scroll

多次调用后,是否有可能不增加设定间隔速度。我正在做自动滚动功能。点击选定的速度按钮后,它会调用函数setInterval。我的问题是,我点击按钮页面的滚动速度越来越快。如何解决我的逻辑错误?

function scroll() {
  var scrollspeed = document.getElementById("scrollspeedval").value;
  if (scrollspeed == 1) {
    window.scrollBy(0, 1);
  } else if (scrollspeed == 2) {
    window.scrollBy(0, 2);
  } else if (scrollspeed == 3) {
    window.scrollBy(0, 4);
  } else if (scrollspeed == 4) {
    window.scrollBy(0, 8);
  } else if (scrollspeed == 5) {
    window.scrollBy(0, 12);
  } else if (scrollspeed == 0) {

  };
}

$("document").ready(function() {
  $(".scrollcl").click(function() {
    var interval_for_autoscroll = setInterval(function() {
      scroll();
    }, 400);
  });
});

2 个答案:

答案 0 :(得分:3)

在开始新的间隔计时器之前,您应该使用clearInterval停止已经运行的间隔计时器:

clearInterval(interval_for_autoscroll); // where interval_for_autoscroll is declared outside the scope of the callback.

这样的事情:



function scroll() {
  var $object = $('.object'),
      angle = $object.data('angle') || 0;

  $object
    .css({ 'transform': 'rotateZ(' + angle + 'deg)' })
    .data('angle', (angle + 10) % 360);
}

$("document").ready(function() {
    var interval_for_autoscroll;
    $('.slow').click(function() {
        clearInterval(interval_for_autoscroll);
        interval_for_autoscroll = setInterval(scroll.bind(window), 400);
    });
    $('.normal').click(function() {
        clearInterval(interval_for_autoscroll);
        interval_for_autoscroll = setInterval(scroll.bind(window), 100);
    });
    $('.fast').click(function() {
        clearInterval(interval_for_autoscroll);
        interval_for_autoscroll = setInterval(scroll.bind(window), 10);
    });
});

.object {
  display: inline-block;
  width: 100px;
  height: 50px;
  background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="object">
</div>
<button class="slow">slow</button>
<button class="normal">normal</button>
<button class="fast">fast</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

看到你正在使用JQuery,我认为.one()对你来说可能是更好的选择,如果你只想触发一次事件。

您可以尝试这样的事情:

$(".scrollcl").one("click",function(){});
相关问题