For Loop never executing (Javascript / Jquery) -


so loop runs if replace$.get('/preceed_with_an.txt', function(data){var ans = data.split('\n')}); ans = ["filler","more filler"] when $.get line in refuses execute loop , nothing ever written console. context, writing code tells if should use or before word. words use on separate lines in preceed_with_an.txt have checked $.get functions , file written array fine.

$(document).on('input',$('#givenword'),function(){       var ans = new array;       $.get('/preceed_with_an.txt', function(data){var ans = data.split('\n')});    (var = 0; < ans.length; i++){     console.log("help");     if (ans[i] == $('#givenword').lower){       var answer = $("#answer");       console.log("an");       $(answer).text("an");       break;     }else{       var answer = $("#answer");       console.log("a")       $(answer).text("a");     }   } }); 

the get() asynchronous, ans.length equal 0 because data return after loop execution.

you have execute for loop in get() callback function:

$.get(url, function(data) {    var arr = data.split(',');    for(...) {       //...    } }); 

execution flow (your code)

  1. create ans array
  2. call get() function
  3. try execute for loop (without available data)
  4. get() return data

asynchronous call

  1. create ans array
  2. call get() function for loop in callback
  3. get() returns data , executes callback --> loop data

example

check console results. if settimeout function called before console.log(), code continued execution , waited callback's answer (after 1 second). when result came out, callback executed:

var def = $.deferred();    def.done(function(data) {    console.log(data);  });    //asynchronus call (delays 1 second)  settimeout(function() {     def.resolve('callback after 1 second')   }, 1000);    //execute  console.log('write something!');    //console results  // 1. write  // 2. callback (after 1 second)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

check these links asynchronous functions:

jquery.get()

async


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -