节流

by Boyanliuu

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>倒计时</title>
    </head>
    <body>

    </body>

</html>

CSS

body{

}

JavaScript

function coloring(){
		let r = Math.floor(Math.random() * 255);
    let g = Math.floor(Math.random() * 255);
        
    let b = Math.floor(Math.random() * 255);
    
    document.body.style.background = `rgb(${r},${g},${b})`;
}

// 第一种方法 使用 set time out
function throttle(func,delay){
let timer;
	return function(){
  	let context = this;
    let args =  arguments;
  	// 如果 timer 被赋值了, 那就是在等待时间间隔内, 就不执行
  	if(timer){
    	return;
    }
  	timer = setTimeout(function(){
    	func.apply(context,args);
      timer = null;
    },delay);
  
  }
}


// 使用 date 相减
function throttle2(func,delay){
let prev = 0;
	return function(){
  	let context = this;
    let args =  arguments;
    let now = new Date();
  	if(now - prev > delay){
			func.apply(context,args);
      prev = now;
    }
      
  }
}

window.addEventListener('resize',throttle2(coloring,2000));