编程语言
首页 > 编程语言> > 计时器方法笔记(JavaScript)

计时器方法笔记(JavaScript)

作者:互联网

计时器方法
1.setInterval与clearlnterval 循环输出
2. setTimeout与clearTimeout 只输出1次
防抖与节流
解决性能问题,开发中常会遇到。
防抖∶对于短时间内多次触发事件的情况,可以使用防抖停止事件持续触发。
节流︰防止短时间内多次触发事件的情况,但是间隔事件内,还是需要不断触发。
window.onscroll事件

防抖( debounce )
滚轮滚动的事件不会连续触发

let timer = null;
window.onscroll = function){
	if(timer !== null){
		clearTimeout(timer);
		}
		timer = setTimeout(() =>{
		console.log("hello world")
		timer = null;
		},2000)
	}

节流( thrqttle )
滚轮滚动的事件按时间间隔触发

let mark = true;
window.onscroll = function(){
	if(mark){
		setTimeout(() =>{
			console.log("hello world");
			mark = true;
		},2000)
	}
	mark = false;
}

标签:触发,防抖,JavaScript,timer,mark,onscroll,计时器,笔记,事件
来源: https://blog.csdn.net/qq_42529941/article/details/122268692