简体   繁体   English

React Native-循环内的setTimeout

[英]React Native - setTimeout inside loop

I noticed a weird behavior with React Native when running setTimeout inside for loop. for循环中运行setTimeout时,我注意到React Native的行为很奇怪。 The code bellow works well on the browser: 下面的代码在浏览器上运行良好:

const myString = '111000111';

for(var x =0; x < myString.length; x++) {
  if (myString[x] == '1') {
    (function(index) {
      setTimeout(()=>{
        console.log('number ' + index);
      }, index * 1000);
    })(x)
  }
}

The result in the browser is: 浏览器中的结果是:

number 0
number 1
number 2
number 6
number 7
number 8

But when running the same code with React Native the result is: 但是当使用React Native运行相同的代码时,结果是:

number 0
number 1
number 8
number 2
number 7
number 6

There's no guarantee when and in which order timeouts are going to be fired and different JS implementations will yield different results (for example if the RN app is busy doing something else it might fire the timeout later). 无法保证将在何时何地触发顺序超时,并且不同的JS实现将产生不同的结果(例如,如果RN应用正忙于执行其他操作,则稍后可能会触发超时)。

If you need them to be in a specific order you'll need to change your implementation, use a queue or something like this. 如果您需要按照特定的顺序排列它们,则需要更改实现,请使用队列或类似的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM