登录  /  注册
首页 > web前端 > js教程 > 正文
在js中如何实现函数去抖(详细教程)
亚连
发布: 2018-06-11 15:53:50
原创
1664人浏览过

这篇文章主要介绍了angular.js和vue.js中实现函数去抖示例(debounce),现在分享给大家,也给大家做个参考。

问题描述

搜索输入框中,只当用户停止输入后,才进行后续的操作,比如发起Http请求等。

学过电子电路的同学应该知道按键防抖。原理是一样的:就是说当调用动作n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间。本文将分别探讨在angular.js和vue.js中如何实现对用户输入的防抖。

angular.js中解决方案

把去抖函数写成一个service,方便多处调用:

.factory('debounce', ['$timeout','$q', function($timeout, $q) {
  // The service is actually this function, which we call with the func
  // that should be debounced and how long to wait in between calls
  return function debounce(func, wait, immediate) {
   var timeout;
   // Create a deferred object that will be resolved when we need to
   // actually call the func
   var deferred = $q.defer();
   return function() {
    var context = this, args = arguments;
    var later = function() {
     timeout = null;
     if(!immediate) {
      deferred.resolve(func.apply(context, args));
      deferred = $q.defer();
     }
    };
    var callNow = immediate && !timeout;
    if ( timeout ) {
     $timeout.cancel(timeout);
    }
    timeout = $timeout(later, wait);
    if (callNow) {
     deferred.resolve(func.apply(context,args));
     deferred = $q.defer();
    }
    return deferred.promise;
   };
  };
 }])
登录后复制

调用方法,在需要使用该功能的controller/directive中注入debounce,也要注入$watch,然后:

$scope.$watch('searchText',debounce(function (newV, oldV) {
  console.log(newV, oldV);
  if (newV !== oldV) {
    $scope.getDatas(newV);
  }
}, 350));
登录后复制

大功告成!

Vue.js中的解决方案

首先在公共函数文件中注册debounce

export function debounce(func, delay) {
 let timer

 return function (...args) {
  if (timer) {
   clearTimeout(timer)
  }
  timer = setTimeout(() => {
   func.apply(this, args)
  }, delay)
 }
}
登录后复制

然后在需要使用的组件中引入debounce,并且在created生命周期内调用:

created() {
 this.$watch('searchText', debounce((newSearchText) => {
  this.getDatas(newSearchText)
 }, 200))
}
登录后复制

大功告成!

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

express搭建查询服务器

使用js自定义trim函数删除两端空格

JavaScript运行原理

vue中全选与反选

详解讲解使用jest测试react native组件

在vue中全选实现数据的绑定及获取

以上就是在js中如何实现函数去抖(详细教程)的详细内容,更多请关注php中文网其它相关文章!

来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学