For Loop never executing (Javascript / Jquery) -
this question has answer here:
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)
- create ans array
- call
get()
function - try execute
for
loop (without available data) get()
return data
asynchronous call
- create ans array
- call
get()
functionfor
loop in callback 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:
Comments
Post a Comment