for里面是采用setInterval遍历二维数组,for循环到最后一个数的时候,才执行setInterval的问题解决

点击播放看效果

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>for里面是采用setInterval遍历二维数组,for循环到最后一个数的时候,才执行setInterval的问题解决</title>
</head>
<body>
<button id="play">播放</button>
<script>
   var sumPath=[
       {
           RowKey:"LNBSCB3F2FD11327120190327091134",
           point:[
           {Longitude: "104.074027",Latitude:"30.707441"},
           {Longitude: "104.109422", Latitude: "30.669311"},
           {Longitude: "104.108675", Latitude: "30.665402"},
           {Longitude: "104.108667", Latitude: "30.665388"}]},
       {
           RowKey:"LNBSCB3F2FD11327120190327103555",
           point:[
               {Longitude: "104.113186", Latitude: "30.663265"},
               {Longitude: "104.114061", Latitude: "30.663335"},
               {Longitude: "104.11468", Latitude: "30.663531"},
               {Longitude: "104.115255", Latitude: "30.663612"},
               {Longitude: "104.11565", Latitude: "30.663767"}
       ]
   }];

    // 怎么按顺序遍历二维数组  ,如果是for里面是一个setInterval,则到for循环到最后一个数的时候,才执行setInterval。 需要用2个setInterval来解决,setInterval是异步的,里面却是同步的
    document.getElementById("play").addEventListener("click",function () {
        firstTraverse();
    });
    var firstIndex=0;// 第一层数组的index
    var secondIndex=0;// 第二层数组的index
    // 第一层的遍历
    function firstTraverse () {
        var firstInterval=setInterval(function () {
            clearInterval(firstInterval);
            if(firstIndex<sumPath.length){
                var point=sumPath[firstIndex].point;
                secondTraverse(point);// 第二层数组传过去
                console.log("第一层的index:"+firstIndex);
            }
        },1000)
    }
    // 第二层的遍历
    function secondTraverse (point) {
        var secondInterval=setInterval(function () {
            if(secondIndex<point.length){
                console.log("第二层的index:"+secondIndex);
                drivePath();
            }else {
                clearInterval(secondInterval);// 要清的是第二个定时器
                secondIndex=0;
                firstIndex++;
                firstTraverse();// 从第一个开始重新调用
                return;
            }
            secondIndex++;
        },1000)
    }
    // 划线
    function drivePath() {

    }
</script>
</body>
</html>

 

posted @ 2019-04-02 13:49  叶韵  Views(982)  Comments(0Edit  收藏  举报