js 函数防抖节流

<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title></title>
	</head>
	<body>
		<input type="text" id="input" />
	</body>
	<script>
		// 函数防抖
		function debounce(fn, Interval) {
			let timer;
			return (event) => {
				if (timer) {
					return false
				}
				timer = setTimeout(() => {
					clearTimeout(timer)
					timer = null
					fn(event)
				}, Interval)
			}
		}
		window.onresize = debounce(function(event) {
			console.log(event)
		}, 1000)

		// 节流
		function throttle(fn, Interval) {
			let timer
			return () => {
				clearTimeout(timer)
				timer = setTimeout(fn, Interval)
			}
		}
		let input = document.getElementById('input')
		input.oninput = throttle(function(event) {
			console.log(input.value)
		}, 1000)
	</script>
</html>

posted @ 2021-12-16 16:18  Smile浅笑  阅读(11)  评论(0编辑  收藏  举报