javascript - 加载单页应用程序的 Javascript 'while' 循环不起作用
问题描述
我正在尝试加载单页应用程序,直到我有一定数量的项目。我的函数传递了正确的新滚动高度,但代码不起作用。这是我的代码,我通过调用scrollInitiate()函数来启动它。我错过了什么?
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function scrollInitiate() {
while ($x('//*[@id="items"]/container').length < 200) {
console.log("attempting");
wait(5000);
scrollIt(document.scrollingElement.scrollHeight);
}
}
function scrollIt(height) {
console.log("scrolling to: " + height);
document.scrollingElement.scrollTo(0, height);
}
解决方案
while
由于 javascript 的阻塞性质,您不能使用在 javascript 中等待。而是使用setTimeout
:
function scrollInitiate() {
if ($x('//*[@id="items"]/container').length < 200) {
console.log("attempting");
scrollIt(document.scrollingElement.scrollHeight);
setTimeout(scrollInitiate, 5000);
}
console.log("success");
}
推荐阅读
- python - 收集列表中的单个变量
- javascript - 为什么注入 javascript 代码是个坏主意
- php - 下拉框依赖于使用 jquery 在另一个下拉框中选择的选项
- python - 如何提高opencv中多尺度模板匹配的准确性
- apache - 命中 API 后立即进入 httpd 的 access_log
- css - 当结果来自其他 css 变量时,CSS 变量不会改变
- python - Odoo11 - `create_invoices()` 错误,需要一个参数,而以前使用两个参数
- ios - 如何从 navigationItem 添加和删除 searchBar
- jquery - 如何在 JQM 中删除动态添加的可折叠项
- oracle - PLSQL 静默添加和删除列