我需要停止一个函数的继续,直到我的 php 脚本从一个需要一些时间加载的文件中获取内容。加载后,我会更新 JavaScript 文件中保存此信息的对象: var setData = seoApp.siteData.result.wordCount;
我创建了一个函数,可以根据 wordCount
的结果更新 html 元素。
我希望我的脚本每隔几秒不断检查 var setData
是否未定义,以等待脚本加载 setData。我想我可以使用以下代码通过 setTimeout 来做到这一点:
for (var i = 0; i < 10; i++) {
setTimeout(function () {
console.log(i);
if(setData !== undefined){
// stops the loop from running again
i = 11
//run if statements here.
}else {
}
}, 6000);
}
好吧,这不起作用。它会等待几秒钟,然后触发 for 循环,而不会等待六秒直到下一个循环。
我做错了什么,这是解决这个问题的最佳方法吗?
根据请求,php 脚本抓取数据:
<?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 that page.
echo "\"bodyCount\": " . substr_count(strip_tags($explodedExplodedBody[0]), $string);
echo " } }";
?>
提前致谢!
最佳答案
您可能已经使用了 XMLHttpRequest
对象的回调函数,在其中将 setData
设置为 PHP 脚本返回的 JSON 输出。这也是您应该启动任何进一步处理的地方:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var setData = JSON.parse(xmlhttp.responseText);
process(setData);
}
};
// ...
function process(setData) {
// Here you can do what you need to do with `setData`
}
如果您想在数据尚未返回时执行某些操作,请使用setInterval
:
var myInterval = setInterval(function () {
console.log('still waiting...');
}, 6000);
...并在获得数据后清除该间隔。但是您可以根据返回的请求轻松执行此操作(这比检查 setData
是否不是 undefined
更好):
function process(setData) {
clearInterval(myInterval);
// Here you can do what you need to do with `setData`
}
您的代码不起作用的原因是您的 for
循环同时创建了 10 个超时,这些超时在 6 秒后一起过期。如果您将给定 setTimeout
的函数命名并在第一个超时到期时将该函数传递给新的 setTimeout
,那么它会起作用:
setTimeout(function repeatTimeout() {
console.log(i);
if(setData !== undefined){
// stops the loop from running again
i = 11
//run if statements here.
} else {
setTimeout(repeatTimeout, 6000);
}
}, 6000);
...但是将 setInterval
与 clearInterval
结合使用会更加简单。
附录
This fiddle具有基于您在 fiddle 中提供的代码的代码,并带有有关更改位置的注释。
关于javascript - 如何让函数等到对象的值不是未定义的 js setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37498358/