函式節流throttle和debounce程式碼演示

admin發表於2018-02-03

下面分享一段程式碼例項,它能夠演示throttle和debounce的作用,進而也就能夠區分這兩者的區別。

underscore.js外掛封裝兩個效果,為了方便,我們就利用此外掛進行相關演示。

程式碼如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
p{
  margin:20px 20px 0px;
  clear:both;
}
.meter{
  margin:10px 20px;
  padding:5px;
  border:1px solid #ccc;
  border-radius:4px;
  font-family:sans-serif;
  display:block;
  float:left;
  clear:left;
  box-shadow:0px 1px 3px 0px rgba(0, 0, 0, 0.2);
  -webkit-touch-callout:none;
  -webkit-user-select:none;
  -khtml-user-select:none;
  -moz-user-select:none;
  -ms-user-select:none;
  user-select:none;
}
.meter:hover{
  background:#ff8;
  cursor:pointer;
}
.meter li{
  border:1px solid #ccc;
  background:#fff;
  width:25px;
  height:20px;
  text-align:center;
  padding-top:8px;
  float:left;
  border-radius:25px;
  margin-right:6px;
  display:inline-block;
  color:#ccc;
}
.meter li:last-child{
  float:none;
  margin:0;
}
.meter li.on{
  background:#2f2;
  box-shadow:inset 0px 1px 0px 2px rgba(0, 0, 0, 0.1);
  border:1px solid #777;
  color:#000;
  font-weight:bold;
  text-shadow:0px 1px #fff;
}
.meter1:after {
  content:"_.throttle()";
  padding:0px 5px;
}
.meter2:after{
  content:"_.debounce()";
  padding:0px 5px;
}
.blink:after{
  font-weight:bold;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script src="http://libs.baidu.com/underscore/1.3.3/underscore.js"></script>
<script type="text/javascript"> 
$(function(){
  function changeMeter(ev){
    var $ul=$(ev.target).closest("ul"),
    numLi=$("li", $ul).length,
    $on=$("li.on", $ul),
    numOn = $on.length;
    if(numLi==numOn){
      $on.removeClass("on");
    } 
    else{
      if(numOn== 0){
        $("li:first", $ul).addClass("on");
      } 
      else{
        $("li.on:last", $ul).next().addClass("on");
      }
    }
  }
  $(".meter1").on("click", _.throttle(changeMeter, 2000));
  $(".meter2").on("click", _.debounce(changeMeter, 2000, true));
 
  $(".meter").on("click",function(ev){
    var $meter = $(ev.target).closest("ul");
    $meter.addClass("blink");
    setTimeout(function(){
      $meter.removeClass("blink");
    }, 50);
  });
});
</script>
</head>
<body>
<ul class="meter meter1">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>
<ul class="meter meter2">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>
</body>
</html>

相關文章