问题


当我单击播放按钮btn-play来快速启动,然后停止输入范围滑块的值递增时,它似乎上升了2,而不是1
当我单击重新启动按钮btn-restart,然后单击播放按钮时,发生了类似的现象


码笔

https://codepen.io/onlyandrewn/pen/EpOXOj?editors=1010

目的


无论是通过startSlider功能还是通过单击播放按钮,输入的值应仅增加一个


scripts.js

$(function() {

  // Input range slider
  let step = 0;

  // Every second increment the value of the input
  var slider = setTimeout(function() {
    incrementStep();
  }, 1000);

  // Increment the value of the input by one
  function incrementStep() {
    $(".slider").val(step++);
  }

  // Start the slider
  function startSlider() {
    timer = setTimeout(startTimer, 1000);
    incrementStep();
  }

  // Stop the slider
  function stopSlider() {
    clearTimeout(slider);
  }

  // Reset the value of the input back to 0
  function restartTimer() {
    step = 0;

    $(".slider").val(0);
  }

  // On click, toggle the play and pause classes
  // If the input is going, stop the slider
  // Otherwise, increment the value of the input
  $(".btn-play").click(function() {
    $(this)
      .find("i")
      .toggleClass("fa-play fa-pause");

    if ($("i").hasClass("fa-play")) {
      stopSlider();
    } else {
      incrementStep();
      startSlider();
    }
  });

  // On click, stop the slider and reset its value to 0
  $(".btn-restart").click(function() {
    stopSlider();
    restartSlider();

    $(".btn-play")
      .find("i")
      .removeClass("fa-pause");
    $(".btn-play")
      .find("i")
      .addClass("fa-play");
  });

  // Upon dragging the slider, change its  value
  $(".slider").on("input", function() {
    $(this).val();
  });
});


index.html

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">

<div class="wrapper">

  <div class="map__info">
    <p class="map__headline">Vacant buildings in St. Louis by neighborhood (1990-2018)</p>
    <p class="map__subheadline">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>

    <p class="map__slider"><span class="is-left">1990</span><input id="slider" class="slider" type="range" value="0" min="0" max="28"><span class="is-right">2018</span></p>

    <div class="button__wrapper">
      <button class="btn btn-play"><i class="fas fa-play"></i> Play</button>
      <button class="btn btn-restart"><i class="fas fa-redo"></i> Restart</button>
    </div>
  </div>
 </div>

最佳答案

播放按钮的逻辑包括对crementStep()的调用和对startSlider()的调用。 startSlider()包括对增量步长()的单独调用。这就是为什么它前进了两次。

而不是使用此:

// Start the slider
function startSlider() {
  timer = setTimeout(startTimer, 1000);
  incrementStep();
}

...

if ($("i").hasClass("fa-play")) {
  stopSlider();
} else {
  incrementStep();
  startSlider();
}


用这个:

// Start the slider
function startSlider() {
  incrementStep();
  timer = setTimeout(startTimer, 1000);
}

...

if ($("i").hasClass("fa-play")) {
  stopSlider();
} else {
  startSlider();
}

07-26 04:33