当前位置:网站首页>Small case of throttling function

Small case of throttling function

2022-06-21 14:28:00 Advanced mathematics volume II half price

Today, let's write a simple throttling function

500ms Multiple internal clicks are only recorded once

The effect is as shown in the picture :

The picture hasn't been sent yet

html and css part :

<body>
     Every time 500 Millisecond can be recorded once 
    <button id="btn"> Am I </button>
    <div id="circle">0</div>
</body>
<style>
#circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: rgb(199, 1, 1);
  line-height: 50px;
  text-align: center;
  color: white;
  opacity: 1.0;
  transition: opacity .25s;
}

#circle.fade {
  opacity: 0.0;
  transition: opacity .25s;
}
</style>

Javascript part :

function throttle(fn, time = 500){
  let timer;
  return function(...args){
    if(timer == null){
      fn.apply(this,  args);
      timer = setTimeout(() => {
        timer = null;
      }, time)
    }
  }
}

btn.onclick = throttle(function(e){
  circle.innerHTML = parseInt(circle.innerHTML) + 1;
  circle.className = 'fade';
  setTimeout(() => circle.className = '', 250);
});    

The implementation of this throttling function is relatively simple , Using the idea of higher-order function , Wrap the original function , timer stay 500ms Then it will be cancelled , That is, setting timer = null, If less than 500ms,timer It's not equal to null Would not have come to this if Inside the function , Will not call function,timer = null When , Will be called once first function.

The next article is to write a small case of anti shake function .

原网站

版权声明
本文为[Advanced mathematics volume II half price]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221424598226.html