javascript - How to have a function wait until an object's value is not undefined js setTimeout -
i need stop function proceeding until php script gets contents file takes bit of time load. once loaded update object holds information on javascript file: var setdata = seoapp.sitedata.result.wordcount;
i have created function updates html elements based on results of wordcount
.
i want script continually check if var setdata
not undefined every few seconds wait script load setdata. thought settimeout using code:
for (var = 0; < 10; i++) { settimeout(function () { console.log(i); if(setdata !== undefined){ // stops loop running again = 11 //run if statements here. }else { } }, 6000); }
well didn't work. waits few seconds , fires loop without waiting 6 seconds until next one.
what doing wrong , best way approach this?
as requested php script scrape data:
<?php $url = $_get["url"]; $string = $_get["keywords"]; libxml_use_internal_errors(true); //prevents warnings, remove if desired $content = file_get_contents($url); $explodedcontent = explode("<title>", $content); $explodedexplodedcontent = explode("</title>", $explodedcontent[1]); $explodedbody = explode("<body>", $content); $explodedexplodedbody = explode("</body>", $explodedbody[0]); echo "{ \"result\": ". "{ "; echo "\"titlecount\": " . substr_count($explodedexplodedcontent[0], $string) . ", "; // title of page. echo "\"bodycount\": " . substr_count(strip_tags($explodedexplodedbody[0]), $string); echo " } }"; ?>
thanks in advance!
you use callback function of xmlhttprequest
object, in set setdata
json output php script has returned. place should initiate further processing:
xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { var setdata = json.parse(xmlhttp.responsetext); process(setdata); } }; // ... function process(setdata) { // here can need `setdata` }
if want while data has not yet been returned, use setinterval
:
var myinterval = setinterval(function () { console.log('still waiting...'); }, 6000);
... , clear interval once have data. can based on request returns (which nicer checking whether setdata
not undefined
):
function process(setdata) { clearinterval(myinterval); // here can need `setdata` }
the reason code did not work for
loop created 10 time-outs @ same time, expired 6 seconds later. have worked if have named function given settimeout
, passed 1 new settimeout
when first timeout expires:
settimeout(function repeattimeout() { console.log(i); if(setdata !== undefined){ // stops loop running again = 11 //run if statements here. } else { settimeout(repeattimeout, 6000); } }, 6000);
... setinterval
combined clearinterval
more straightforward.
addendum
this fiddle has code based on code presented in fiddle, comments on make changes.
Comments
Post a Comment