Search code examples
javascriptlet

how do i do asyncronous calls without let?


I found out yesterday that the iphone does not allow the use of let. This leaves me woundering how to deal with asyncronous calls like ajax and time outs. Bellow is an example code showing the difference. How can I make the var half function the same as the let half without using keywords that some devices won't like?

$("body").append("VAR:<br>");  
for (var i=0;i<10;i++) {
    setTimeout(function(){
    $("body").append(i +"<br>");  
  },Math.random()*1000);
}

//make lets come after var
setTimeout(function(){

$("body").append("LET:<br>");  
for (let i=0;i<10;i++) {
    setTimeout(function(){
    $("body").append(i +"<br>");  
  },Math.random()*1000);
}
},2000);

JSFiddle


Solution

  • Without an IIFE your code will have only one instance of i and will always show 10. For creating an local variable you need a function.Every function has its own local variables. In the code I call an IIFE and pass the i as an parameter. Every function gets its own copy of current i.

    In short, if you want an local variable which is declared with the var keyword, you need a function.In our case immediately invoked function

    $("body").append("VAR:<br>");  
    for (var i=0;i<10;i++) {
        (function(e){
          setTimeout(function(){
             $("body").append(e +"<br>");  
          },Math.random()*1000);
        })(i);    
    }
    

    See the code

    var body = $("body")
    
    body.append("VAR:<br>");  
    for (var i=0;i<10;i++) {
        (function(e){
          setTimeout(function(){
             body.append(e +"<br>");  
          },Math.random()*1000);
        })(i);    
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <body>
      
    </body>

    and this is your JSFIDDLE