前端面试之手写防抖节流

在前端开发中针对连续触发和不可控的高频触发问题,防抖和节流给出了两种解决策略

一、首先讲一下什么是防抖?

**防抖:**当一个事件被触发的时候,设置一个周期来延时执行动作,若在该周期内事件又被触发,则重新设定周期,直到周期结束,执行动作。

用简单的话来解释的话,防抖就好比坐电梯,如果5s中没有人在进入的话,就关门,如果在5s内又有人进入电梯了,那么这个5s周期又重新刷新了。

二、什么是节流?

**节流:**节流会有一个固定的周期,在这个周期内,只执行一次动作,若有新事件触发,不会执行。直到周期结束,才可以再次触发执行动作。

通过游戏来解释防抖节流:防抖就是回城,节流就是按技能(想想是不是这样的)

1、手写防抖

function debounce(fn, delay){
	let timer = null;
	return function(...args){
		// 清除定时器
		clearTimeout(timer);
		timer = setTimeout(() => {
			fn.apply(this, args);
		}, delay)
	}
}

2、手写节流

// 1、时间戳方式
function(fn, delay){
	let startTime = 0;
	return function(...args){
		let nowTime = Date.now();
		if(nowTime - startTime > delay){
			fn.apply(this, args);
			startTime = Date.now();
		}
	}
}
// 2、setTimeout实现
function(fn, delay){
	let timer = null;
	return function(...args){
		if(!timer){
			timer = setTimeout(() => {
				fn.apply(this, args);
				timer = null;
			}, delay)
		}	
	}
}
### 防抖函数的实现 防抖(debounce)是一种常用的前端优化技术,主要用于限制触发频率,例如在搜索框输入时减少请求次数。基本思想是,在事件被触发后,等待一段时间,如果在这段时间内没有再次触发,则执行相应的处理逻辑。 ```javascript function debounce(fn, delay) { let timer; return function() { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, arguments); }, delay); }; } // 示例使用 const searchInput = document.getElementById('search'); searchInput.addEventListener('input', debounce(function(e) { console.log('发送请求:', e.target.value); }, 300)); ``` ### 节流函数的实现 节流(throttle)也是一种优化技术,用于确保某个函数在一定时间间隔内只执行一次,常用于窗口调整、滚动等高频事件中。 ```javascript function throttle(fn, delay) { let lastTime = 0; return function() { const now = Date.now(); if (now - lastTime >= delay) { fn.apply(this, arguments); lastTime = now; } }; } // 示例使用 window.addEventListener('resize', throttle(function() { console.log('窗口大小改变'); }, 500)); ``` ### 实现一个计数器 实现一个简单的计数器,可以通过闭包来保持状态,并提供增加和获取当前值的方法。 ```javascript function createCounter() { let count = 0; return { increment: function() { count++; }, getCount: function() { return count; } }; } const counter = createCounter(); counter.increment(); console.log(counter.getCount()); // 输出 1 ``` ### 获取 URL 参数 通过解析 `window.location.search` 来提取 URL 中的参数。 ```javascript function getUrlParams(url) { const params = {}; const parser = new URL(url).searchParams; for (const [key, value] of parser.entries()) { params[key] = value; } return params; } const url = 'https://example.com?name=JohnDoe&age=30'; console.log(getUrlParams(url)); // { name: 'JohnDoe', age: '30' } ``` ### 手写 `new` 的执行过程 `new` 操作符会创建一个新对象,并将其原型指向构造函数的 `prototype`,然后调用构造函数并绑定 `this`。 ```javascript function myNew(constructor, ...args) { const obj = Object.create(constructor.prototype); const result = constructor.apply(obj, args); return typeof result === 'object' && result !== null ? result : obj; } function Person(name) { this.name = name; } const person = myNew(Person, 'Alice'); console.log(person.name); // 输出 Alice ``` ### 手写 `Object.create()` `Object.create()` 方法创建一个新对象,使用现有的对象作为新对象的原型。 ```javascript function myCreate(proto) { function F() {} F.prototype = proto; return new F(); } const parent = { greet: 'Hello' }; const child = myCreate(parent); console.log(child.greet); // 输出 Hello ``` ### `instanceof` 实现 `instanceof` 运算符用于检测构造函数的 `prototype` 属性是否出现在某个实例对象的原型链上。 ```javascript function myInstanceOf(instance, constructor) { let proto = Object.getPrototypeOf(instance); while (proto) { if (proto === constructor.prototype) { return true; } proto = Object.getPrototypeOf(proto); } return false; } function Person() {} const person = new Person(); console.log(myInstanceOf(person, Person)); // 输出 true ``` ### 实现红黄绿循环打印 这是一个经典的异步编程问题,要求按顺序打印红、黄、绿三种颜色,并且循环进行。 ```javascript function printColors() { const colors = ['red', 'yellow', 'green']; let index = 0; function nextColor() { console.log(colors[index]); index = (index + 1) % colors.length; setTimeout(nextColor, 1000); } nextColor(); } printColors(); // 每秒依次输出 red, yellow, green ``` ### 使用 `Promise` 实现异步加载图片 通过 `Promise` 来实现异步加载图片的功能。 ```javascript function loadImageAsync(url) { return new Promise((resolve, reject) => { const image = new Image(); image.onload = resolve.bind(null, image); image.onerror = reject; image.src = url; }); } loadImageAsync('https://example.com/image.jpg') .then(image => { document.body.appendChild(image); }) .catch(error => { console.error('加载图片失败:', error); }); ``` ### 实现数组的 `push`、`filter`、`map` 方法 这些方法是数组操作的基础,理解它们的实现有助于深入掌握 JavaScript。 #### `push` 方法 ```javascript Array.prototype.myPush = function(...items) { for (let i = 0; i < items.length; i++) { this[this.length] = items[i]; } return this.length; }; const arr = [1, 2]; arr.myPush(3, 4); console.log(arr); // 输出 [1, 2, 3, 4] ``` #### `filter` 方法 ```javascript Array.prototype.myFilter = function(callback) { const result = []; for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { result.push(this[i]); } } return result; }; const filtered = [1, 2, 3].myFilter(x => x > 1); console.log(filtered); // 输出 [2, 3] ``` #### `map` 方法 ```javascript Array.prototype.myMap = function(callback) { const result = []; for (let i = 0; i < this.length; i++) { result.push(callback(this[i], i, this)); } return result; }; const mapped = [1, 2, 3].myMap(x => x * 2); console.log(mapped); // 输出 [2, 4, 6] ``` ### 使用 `setTimeout` 实现 `setInterval` 通过递归调用 `setTimeout` 来模拟 `setInterval` 的行为。 ```javascript function mySetInterval(fn, delay) { function interval() { fn(); setTimeout(interval, delay); } setTimeout(interval, delay); } mySetInterval(() => { console.log('每隔一秒打印一次'); }, 1000); ``` ### 手写 `bind` `bind` 方法返回一个新的函数,该函数会将原函数的 `this` 绑定到指定的对象。 ```javascript Function.prototype.myBind = function(context, ...args) { const fn = this; return function(...innerArgs) { return fn.apply(context, [...args, ...innerArgs]); }; }; function greet(greeting) { console.log(`${greeting}, ${this.name}`); } const person = { name: 'Alice' }; const boundGreet = greet.myBind(person, 'Hello'); boundGreet(); // 输出 Hello, Alice ``` ### 实现 `jsonp` JSONP 是一种跨域请求的技术,通过动态创建 `<script>` 标签来实现。 ```javascript function jsonp(url, callbackName, success) { const script = document.createElement('script'); script.src = `${url}?callback=${callbackName}`; window[callbackName] = function(data) { success(data); document.head.removeChild(script); delete window[callbackName]; }; document.head.appendChild(script); } jsonp('https://api.example.com/data', 'handleResponse', data => { console.log(data); }); ``` ### 手写一个深度比较 `isEqual` 深度比较两个对象是否相等。 ```javascript function isEqual(obj1, obj2) { if (obj1 === obj2) return true; if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 == null || obj2 == null) return false; const keys1 = Object.keys(obj1); const keys2 = Object.keys(obj2); if (keys1.length !== keys2.length) return false; for (let key of keys1) { if (!keys2.includes(key) || !isEqual(obj1[key], obj2[key])) { return false; } } return true; } const obj1 = { a: 1, b: { c: 2 } }; const obj2 = { a: 1, b: { c: 2 } }; console.log(isEqual(obj1, obj2)); // 输出 true ``` ### 手写深拷贝 深拷贝可以避免引用类型的共享问题。 ```javascript function deepClone(obj, hash = new WeakMap()) { if (obj instanceof Date) return new Date(obj); if (obj instanceof RegExp) return new RegExp(obj); if (typeof obj !== 'object' || obj === null) return obj; if (hash.has(obj)) return hash.get(obj); const clone = Array.isArray(obj) ? [] : {}; hash.set(obj, clone); for (let key in obj) { if (obj.hasOwnProperty(key)) { clone[key] = deepClone(obj[key], hash); } } return clone; } const original = { a: 1, b: { c: 2 } }; const cloned = deepClone(original); cloned.b.c = 3; console.log(original.b.c); // 输出 2 ``` ### 手写数组去重 去除数组中的重复元素。 ```javascript function unique(arr) { const seen = {}; return arr.filter(item => { const key = typeof item + JSON.stringify(item); return seen.hasOwnProperty(key) ? false : (seen[key] = true); }); } const arr = [1, 2, 2, 3, 4, 4, 5]; console.log(unique(arr)); // 输出 [1, 2, 3, 4, 5] ``` ### 大数相加 处理超过 JavaScript 数字精度的大数相加。 ```javascript function addBigNumbers(num1, num2) { let i = num1.length - 1; let j = num2.length - 1; let carry = 0; let result = ''; while (i >= 0 || j >= 0 || carry > 0) { const digit1 = i >= 0 ? parseInt(num1[i--]) : 0; const digit2 = j >= 0 ? parseInt(num2[j--]) : 0; const sum = digit1 + digit2 + carry; carry = Math.floor(sum / 10); result = (sum % 10) + result; } return result; } console.log(addBigNumbers('12345678901234567890', '98765432109876543210')); // 输出 111111111011111111100 ``` ### 设计一个图片懒加载 SDK 图片懒加载是一种常见的性能优化手段,可以在图片进入视口时再加载。 ```javascript class LazyLoad { constructor(images) { this.images = images; this.observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; img.src = img.dataset.src; this.observer.unobserve(img); } }); }, { rootMargin: '0px 0px 200px 0px' }); this.init(); } init() { this.images.forEach(img => this.observer.observe(img)); } } const images = document.querySelectorAll('img[data-src]'); new LazyLoad(images); ``` ### 用正则实现 `trim()` 清除字符串两端的空格。 ```javascript String.prototype.myTrim = function() { return this.replace(/^\s+|\s+$/g, ''); }; const str = ' Hello World! '; console.log(str.myTrim()); // 输出 "Hello World!" ``` ### 简单写一个 Webpack 配置文件 Webpack 是一个模块打包工具,广泛用于现代前端开发中。 ```javascript const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }, { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, devServer: { contentBase: './dist' } }; ``` ### React 自定义 Hook `useCountdown` React 自定义 Hook 可以帮助我们复用组件逻辑。 ```javascript import { useState, useEffect } from 'react'; function useCountdown(seconds) { const [timeLeft, setTimeLeft] = useState(seconds); useEffect(() => { if (timeLeft <= 0) return; const timer = setInterval(() => { setTimeLeft(prev => prev - 1); }, 1000); return () => clearInterval(timer); }, [timeLeft]); return timeLeft; } function CountdownComponent() { const timeLeft = useCountdown(10); return <div>{timeLeft > 0 ? `倒计时: ${timeLeft}` : '结束'}</div>; } ``` ### 实现 `call` 和 `apply` 方法 `call` 和 `apply` 都可以用来改变函数执行时的 `this` 上下文。 #### `call` 方法 ```javascript Function.prototype.myCall = function(context, ...args) { context = context || window; const fnSymbol = Symbol('fn'); context[fnSymbol] = this; const result = context[fnSymbol](...args); delete context[fnSymbol]; return result; }; function greet(greeting) { console.log(`${greeting}, ${this.name}`); } const person = { name: 'Alice' }; greet.myCall(person, 'Hello'); // 输出 Hello, Alice ``` #### `apply` 方法 ```javascript Function.prototype.myApply = function(context, args = []) { context = context || window; const fnSymbol = Symbol('fn'); context[fnSymbol] = this; const result = context[fnSymbol](...args); delete context[fnSymbol]; return result; }; function greet(greeting) { console.log(`${greeting}, ${this.name}`); } const person = { name: 'Alice' }; greet.myApply(person, ['Hello']); // 输出 Hello, Alice ``` ### 写一个前端图片压缩的工具方法 前端图片压缩可以通过 Canvas 实现。 ```javascript function compressImage(file, maxSize, quality = 0.7) { return new Promise((resolve) => { const reader = new FileReader(); reader.onload = (e) => { const img = new Image(); img.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); let width = img.width; let height = img.height; if (width > height && width > maxSize) { height *= maxSize / width; width = maxSize; } else if (height > maxSize) { width *= maxSize / height; height = maxSize; } canvas.width = width; canvas.height = height; ctx.drawImage(img, 0, 0, width, height); canvas.toBlob(blob => { resolve(new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() })); }, 'image/jpeg', quality); }; img.src = e.target.result; }; reader.readAsDataURL(file); }); } // 使用示例 document.querySelector('input[type="file"]').addEventListener('change', async (event) => { const file = event.target.files[0]; const compressedFile = await compressImage(file, 800, 0.6); console.log(compressedFile); }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩浩不睡觉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值