函数节流及手机端点击延迟200ms解决方法

  不论是H5开发还是微信小程序,手机端点击都会有300ms的延迟,在实际项目中,会到此频繁触发,如有接口会频繁的请求接口,除了会引起不必要的多次请求还会导致数据有问题。下面有二种方式来处理这个问题:

1、节流

  节流的目的是防止过多频繁的请求。导致资源的浪费,影响性能。

function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined)  gapTime = 1500
       let _lastTime = null
       return function () {    // 返回新的函数
           let _nowTime = + new Date()
           if (_nowTime - _lastTime > gapTime || !_lastTime) {
                fn.apply(this, arguments)   //将this和参数传给原函数
              _lastTime = _nowTime
           }
       }
}
使用方法:
 tap: util.throttle(function (e) {
  console.log(this)
  console.log(e)
  console.log((new Date()).getSeconds())
 }, 1000)
 
2、消除手机移动端的点击延迟。
  通常移动端点击延迟有许多中方式,这里会介绍一二种方式,fastclick 是一个很好用的方法。引入fastclick。
纯Javascript版:
if ( 'addEventListener' in document ) {
  document.addEventListener( 'DOMContentLoaded',function(){
    FastClick.attach( document.body)
  } )
}
jqery版:
$(function(){
  FastClick.attach($('body'))
})
但是在使用中需要过滤掉许多不适用这个方式的元素,如a标签 这时在标签上添加 class needsclick
 
下面是fastclick的详细用法
<script src="https://as.alipayobjects.com/g/component/fastclick/1.0.6/fastclick.js"></script>
<script>
  if ('addEventListener' in document) {
    document.addEventListener('DOMContentLoaded', function() {
      FastClick.attach(document.body);
    }, false);
}
  if(!window.Promise) {
    document.writeln('<script src="https://as.alipayobjects.com/g/component/es6-promise/3.2.2/es6-promise.min.js" '+'>'+'<'+'/'+'script>');
  }

</script>
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/xqmyhome/p/11250215.html