JavaScript----同步异步和排他思想

同步和异步

  • 同步就是先后执行,只有当当前的执行完,才能执行下一个,好比一个隧道只能一辆车一辆车的过
  • 异步就是同时执行,好比一个隧道可以同时驶过两辆车
  • 注意点:
    • 默认的所有的代码都是同步操作的
    • 默认的所有的函数调用都是异步的
  • 经典案例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>93-同步和异步</title>
</head>
<body>
<button>我是第1个按钮</button>
<button>我是第2个按钮</button>
<button>我是第3个按钮</button>
<button>我是第4个按钮</button>
<button>我是第5个按钮</button>
<script>
var btns = document.querySelectorAll("button");
for(var i = 0,len = btns.length;i<len;i++){
      btns[i].onclick = function(){
      console.log("我是第",i,"个按钮")
  }
}
//当按下按钮的时候永远输出我是第5个按钮
</script>
  • 解释: 当函数调用的时候,for循环已经执行完毕,执行完毕后的i永远等于5

解决方案

  • 使用闭包, 保存每次循环的值, 实现异步效果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>93-同步和异步</title>
</head>
<body>
<button>我是第1个按钮</button>
<button>我是第2个按钮</button>
<button>我是第3个按钮</button>
<button>我是第4个按钮</button>
<button>我是第5个按钮</button>
<script>
var btns = document.querySelectorAll("button");
for(var i = 0,len = btns.length;i<len;i++){
     (function(index){
       btns[index].onclick = function(){
      console.log("我是第",index,"个按钮")
  }
})(i)
}
</script>
</body>
</html>
  • 解析: 当执行for循环后,执行自调函数,将参数i传递给index, 由于点击事件的函数用到了外界的index, 因此index得以被保存, 同样i的值也被记录下来
  • 这里的自调函数是0级作用域, 自调函数内的函数是一级作用域, 点击时间的函数是二级作用域
(function(index){
       btns[index].onclick = function(){
      console.log("我是第",index,"个按钮")
  }
})(i)

//等价于
function test(index){
       btns[index].onclick = function(){
      console.log("我是第",index,"个按钮")
  }
}
test(i)

排他思想

  • 需求: 鼠标移到哪个li上面, li的背景颜色变红,并且其他的背景颜色为白色
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>94-高级排它</title>
    <style>
        .selected{
            background: red;
        }
    </style>
</head>
<body>
<ul>
    <li class="selected">我是第1个li</li>
    <li>我是第2个li</li>
    <li>我是第3个li</li>
    <li>我是第4个li</li>
    <li>我是第5个li</li>
</ul>
<script>
var oLis = document.querySelectorAll("ul>li");
var currentIndex = 0;
for(var i = 0,len = oLis.length;i < len;i++){
  (function(index){
    oLis[index].onmouseenter = function(){
    this.className = ".select"
    oLis[currentIndex].className = ""
    currentIndex = index.
  })(i)
}
</script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,657评论 8 265
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,801评论 1 45
  • 2018年5月3日 今天是我和你分开十年后相遇的日子,分开这么多年来第一次相见,感觉真好,还是那么亲切,感觉你依然...
    x秀丽x阅读 136评论 0 0
  • 【2017年大德盛世 1000万目标势必达成】 【 大德今年势必会孵化出二个年薪30 万以上,三个年薪 20万以上...
    大德帅帅阅读 201评论 0 0
  • 过去独犹不及,来世仍如异形。造极两化遂空,万物轮回遒渡。苦吟两行断泪,别宵寒凛无垠。元夜归然思砚,冷风不解思结。象...
    蒙马特18区阅读 212评论 0 0