如何使用给定的时间数组更改setTimeout时间

时间:2018-10-27 08:36:33

标签: javascript arrays settimeout

<div id="show"></div>

<script>

var s = document.getElementById("show");

//let say given time array is:
//time will be 1:00,2:30,3:50 so on.....
//we need to convert time in millisecond....

var gtime = new Array("915000", "750000", "605000");

//just want to put in For loop

for(var i=0, i > 3, i++){

//put time array here

setTimeout(function(){
  s.innerHTML = s.innerHTML + //put time each array here.toString();
}, //put time each array here);

}
</script>
  

就像在FOR LOOP中一样:

     

Ist LOOP setTimeout(function(){         s.innerHTML = s.innerHTML + //将每个数组放在此处的时间。toString();       },915000);

     

第二个循环setTimeout(function(){         s.innerHTML = s.innerHTML + //将每个数组放在此处的时间。toString();       },750000);

     

第三环setTimeout(function(){         s.innerHTML = s.innerHTML + //将每个数组放在此处的时间。toString();       },605000);

2 个答案:

答案 0 :(得分:1)

您获取时间的循环不正确,可以使用var i in gtimegtime[i])来获取实际时间。

注意: 您需要另一个参数来在setTimeout()函数

中获得正确的时间。

var s = document.getElementById("show");

//let say given time array is:
//time will be 1:00,2:30,3:50 so on.....
//we need to convert time in millisecond....

var gtime = new Array("9150", "7500", "6050");

var j = 0;

for(var i in gtime){

//put time array here

   setTimeout(function(){
     $("#show").html(gtime[j]);
     j++;
   },Number(gtime[i]));

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

Time value: <div id="show"></div>

答案 1 :(得分:0)

请尝试以下操作:

<script>

var s = document.getElementById("show");

//let say given time array is:
//time will be 1:00,2:30,3:50 so on.....
//we need to convert time in millisecond....

var gtime = new Array("915000", "750000", "605000");

//just want to put in For loop

for(var i=0, i < 3, i++){

//put time array here

setTimeout(function(){
  s.innerHTML = s.innerHTML + gtime[i];
}, gtime[i]);

}
</script>