【JavaScript】
一、防抖和节流
1. 防抖函数的实现
一个需要频繁触发的函数,在规定时间内只让最后一次生效,前面不生效。就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
<!DOCTYPE html>
<html>
<head>
<title>防抖函数</title>
<style>
</style>
</head>
<body>
<div>
<button id='btn'>防抖</button>
</div>
<script>
function debounce(fn,delay){
let timeout = null;
return function(){
if(timeout !== null){
clearTimeout(timeout);
}
timeout = setTimeout(fn.apply(this),delay);
}
}
function fn(){
console.log("触发时间:" + new Date());
}
document.getElementById('btn').addEventListener('click',debounce(fn,500));
</script>
</body>
</html>
2. 节流函数的实现
有个需要频繁触发的函数,出于性能优化角度,在规定的时间内,只让函数触发的第一次生效,后面的不生效。
<!DOCTYPE html>
<html>
<head>
<title>节流函数</title>
<style>
</style>
</head>
<body>
<div>
<button id='btn'>节流</button>
</div>
<script>
function throttle(fn,delay){
// 记录上一次触发的时间
var lasttime = 0 ;
// 通过闭包的方式使用lasttime变量,每次都是上次的时间
return function(){
//
var nowtime = Date.now();
if(nowtime-lasttime>delay){
// 修正this函数问题
fn.call(this);
// 同步时间
lasttime = nowtime;
}
}
}
function fn(){
console.log("触发时间:" + new Date());
}
document.getElementById('btn').addEventListener('click',throttle(fn,2000));
</script>
</body>
</html>
3. 应用场景
函数防抖的应用场景:
连续的事件,只需触发一次回调的场景有:
- 搜索框搜索输入。只需用户最后一次输入完,再发送请求。
- 窗口大小Resize。只需窗口调整完成后,计算窗口大小。防止重复渲染。
- 表单验证、手机号、邮箱验证输入检测。
- 按钮点击事件。
函数节流的应用场景:
间隔一段时间执行一次回调的场景有:
- 按钮点击事件。高频点击提交,表单重复提交。
- 滚动加载,加载更多或滚到底部监听。
- 拖拽事件。
- 计算鼠标移动的距离 (mousemove)。
https://www.cnblogs.com/piaobodewu/p/10395858.html
二、DFS 和 BFS
深度优先搜索就是自上而下的遍历,广度优先搜索则是逐层遍历,如图所示:
深度优先搜索:1,2-1,3-1,3-2,2-2,3-3,3-4,2-3,3-5,3-6
广度优先搜索:1,2-1,2-2,2-3,3-1,3-2,3-3,3-4,3-5,3-6
示例一:
const data = [
{
name: 'a',
children: [
{ name: 'b', children: [{ name: 'e' }] },
{ name: 'c', children: [{ name: 'f' }] },
{ name: 'd', children: [{ name: 'g' }] },
],
},
{
name: 'a2',
children: [
{ name: 'b2', children: [{ name: 'e2' }] },
{ name: 'c2', children: [{ name: 'f2' }] },
{ name: 'd2', children: [{ name: 'g2' }] },
],
}
]
1. 深度优先 DFS
function dfs(data) {
const result = [];
data.forEach(item => {
const map = data => {
result.push(data.name);
if(data.children){
data.children.forEach(child => map(child));
}
}
map(item);
})
return result.join(',');
}
console.log(dfs(data)); // a,b,e,c,f,d,g,a2,b2,e2,c2,f2,d2,g2
2. 广度优先 BFS
// 广度遍历, 创建一个执行队列, 当队列为空的时候则结束
function bfs(data) {
let result = [];
let queue = data;
while (queue.length > 0) {
[...queue].forEach(child => {
queue.shift();
result.push(child.name);
if(child.children){
queue.push(...child.children);
};
});
}
return result.join(',');
}
console.log(bfs(data)); // a,a2,b,c,d,b2,c2,d2,e,f,g,e2,f2,g2
示例二:
const tree = {
value: "-",
left: {
value: '+',
left: {
value: 'a',
},
right: {
value: '*',
left: {
value: 'b',
},
right: {
value: 'c',
}
}
},
right: {
value: '/',
left: {
value: 'd',
},
right: {
value: 'e',
}
}
}
1. 深度优先 DFS(也是二叉树的先序遍历)
// 深度优先搜索 栈
// 递归
function dfs(tree) {
let result = [];
let dg = function(node){
if(node){
result.push(node.value);
if(node.left) dg(node.left);
if(node.right) dg(node.right);
}
}
dg(tree);
return result.join(',');
}
console.log(dfs(tree)); // -,+,a,*,b,c,/,d,e
// 深度优先搜索 栈
// 非递归
function dfs(tree) {
let result = [];
let stack = [tree];
while(stack.length){
let node = stack.pop();
result.push(node.value);
if(node.right) stack.push(node.right);
if(node.left) stack.push(node.left);
}
return result.join(',');
}
console.log(dfs(tree)); // -,+,a,*,b,c,/,d,e
2. 广度优先 BFS
// 广度优先搜索 队列
// 使用shift修改数组
function bfs(tree) {
let result = [];
let queue = [tree];
while(queue.length){
let node = queue.shift();
result.push(node.value);
if(node.left) queue.push(node.left);
if(node.right) queue.push(node.right);
}
return result.join(',');
}
console.log(bfs(tree)); // -,+,/,a,*,d,e,b,c
// 广度优先搜索 队列
// 使用指针
function bfs(tree) {
let result = [];
let queue = [tree];
let pointer = 0;
while(pointer < queue.length){
let node = queue[pointer++];
result.push(node.value);
if(node.left) queue.push(node.left);
if(node.right) queue.push(node.right);
}
return result.join(',');
}
console.log(bfs(tree)); // -,+,/,a,*,d,e,b,c
两者的区别:
对于算法来说,无非就是时间换空间,空间换时间:
- 深度优先不需要记住所有的节点,所以占用空间小,而广度优先需要先记录所有的节点占用空间大
- 深度优先有回溯的操作(没有路走了需要回头),所以相对而言时间会长一点
- 深度优先采用的是堆栈的形式, 即先进后出,广度优先则采用的是队列的形式, 即先进先出
https://www.cnblogs.com/zzsdream/p/11322060.html
js 中二叉树的深度遍历与广度遍历(递归实现与非递归实现) - 简书
js深度优先遍历和广度优先遍历实现_深度优先遍历和广度优先遍历js-CSDN博客
三、setTimeout 实现重复定时器(即实现 setIntevel)
setTimeout(function(){
// 处理中
setTimeout(arguments.callee, interval);
// arguments.callee 用来获取对当前执行的函数的引用
},interval)
// 完整代码及其调用
function defineSetInterval(fn,interval){
setTimeout(function(){
// 执行内容
fn();
// arguments.callee 用来获取对当前执行的函数的引用
setTimeout(arguments.callee, interval);
},interval)
}
// 调用
defineSetInterval(fn,interval);
好处:在前一个定时器代码执行之前,不会向队列插入新的定时器代码,确保不会有任何缺失的间隔。而且,它可以保证在下一次定时器代码执行之前,至少要等待指定的间隔,避免了连续的运行。
应用:将一个<div>元素向右移动,当左坐标在200像素的时候停止。
setTimeout(function(){
var div = document.getElementById("myDiv");
left = parseInt(div.style.left) + 5;
div.style.left = left +"px";
if(left < 200){
setTimeout(arguments.callee, 50);
}
},50)
应用拓展:将一个<div>元素左右移动。
<!DOCTYPE html>
<html>
<head>
<title>重复定时器的应用</title>
<style>
#main{
width: 100%;
height: 200px;
position: relative;
border: 1px solid black;
}
#myDiv{
width: 100px;
height: 100px;
position: absolute;
top: 50px;
left: 0;
border: 1px solid red;
}
</style>
</head>
<body>
<div id="main">
<div id='myDiv'>左右移动</div>
</div>
<script>
let distance = 10;
let bool = true;
setTimeout(function(){
let div = document.getElementById("myDiv");
let left = parseInt(div.currentStyle ? div.currentStyle.left : getComputedStyle(div,null).left);
left = bool ? left + distance : left - distance;
div.style.cssText = 'left:'+ left +'px;'
let main = document.getElementById("main");
let mainWidth = parseInt(main.clientWidth);
let width = parseInt(div.currentStyle ? div.currentStyle.width : getComputedStyle(div,null).width);
let t = mainWidth - width - distance;
bool = left < t ? (left === 0 ? true : bool) : false;
setTimeout(arguments.callee, 50);
},50)
</script>
</body>
</html>
四、Ajax 请求
// 创建对象
var xhr = new XMLHttpRequest();
// 绑定监听对象
xhr.onreadystatechange = function () {
// 监听readyState和status
if (xhr.readyState === 4 && xhr.status === 200) {
var value = xhr.responseText; // 获取数据
alert(value);
}
}
// 调用open方法,
// 指定请求的路径,
// 是否是异步,true:异步,false:同步
// get方法,参数放在url的?后面
xhr.open("get", url, true);
// post方法
// xhr.open("post", url, true);
// xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 发送请求
xhr.send();
关于 xhr 的超时设定、加载事件及进度事件:
各个浏览器虽然都支持 xhr,但还是有些差异。
1、超时设定
IE8 为 xhr 对象添加了一个 timeout 属性,表示请求在等待响应多少毫秒后就终止。在给 timeout 设置一个数值后,如果在规定的时间内浏览器还没有接收到响应,那么就会触发 timeout 事件,进而会调用 ontimeout 事件处理程序。
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(event){
try {
if(xhr.readyState == 4){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText);
} else {
alert("Request was unsuccessful:" + xhr.status);
}
}
} catch(ex){
// 假设ontimeout事件处理程序处理
}
};
xhr.open("get", url, true);
xhr.timeout = 1000;
xhr.ontimeout = function(){
alert("Request did not return in a second.");
};
xhr.send(null);
2、加载事件
Firfox 在实现 xhr 对象的某个版本时,曾致力于简化异步交互模型。于是引入 load 事件,用以代替 readystatechange 事件。响应接收完毕后将触发 load 事件,因此也就没有必要去检查 readyState 属性了。
var xhr = new XMLHttpRequest();
xhr.onload = function(event){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText);
} else {
alert("Request was unsuccessful:" + xhr.status);
}
};
xhr.open("get", url, true);
xhr.send(null);
只要浏览器接收到服务器的响应,不管其状态如何,都会触发load事件。而这意味着你必须检查 status 属性,才能确定数据是否真的已经可用了。
3、进度事件
Mozilla 对 xhr 对象的另一个革新是添加了 progress 事件,这个事件会在浏览器接受新数据期间周期性的触发,而 onprogress事件处理程序 会接收到一个 event 对象,其 target 属性是 xhr 对象,但包含着两个额外的属性:position 和 totalSize。其中 position 表示已经接受的字节数,totleSize 表示根据 Content-Length 响应头部确定的预期字节数。
var xhr = new XMLHttpRequest();
xhr.onload = function(event){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText);
} else {
alert("Request was unsuccessful:" + xhr.status);
}
};
xhr.onprogress = function(event){
var divStatus = document.getElementById("status");
divStatus.innerHTML = "Received" + event.position + "of" + event.totalSize +"bytes";
};
xhr.open("get", url, true);
xhr.send(null);
END