【发布时间】:2017-08-24 18:01:30
【问题描述】:
我有一个返回真或假的函数。现在我想在函数返回“true”后执行一些代码。
该函数确定元素是否在屏幕上可见。我是从here 拿来的。
元素在页面加载后 1-2 秒显示。但由于这也与用户的互联网连接有关,我不想使用 setTimout 函数。 我尝试了一些事情并发现它在 if/else 语句中有效,但在 when/then 中无效。任何想法,这里出了什么问题?
我测试了一些东西,见下面的代码
//below if else statement works fine and logs the correct result
if($(".myClass").isOnScreen()==true){
console.log("true");
}
else{console.log("false");}
//however i would like to use this one and it doesn't seem to work
$.when($(".myClass").isOnScreen()==true).then(function(){
console.log($(".myClass").isOnScreen());
setTimeout(function(){
console.log($(".myClass").isOnScreen());
},1000);
});
when / then 语句的实际作用: 只要函数 isOnScreen 运行,它就会运行,但不会等到返回响应为真。因此控制台日志总是错误的。 然后我实现了一个超时(仅用于测试目的)。在timeOut跑完之后,控制台日志一直是假的。
它应该做什么: 当结果为真后,应该运行when/语句。
【问题讨论】:
-
isOnScreen看起来像一个sync操作,如果你将它包装在承诺/超时中,你最终会出现不一致的行为...... -
您链接到的逻辑设计为在
scroll事件处理程序中使用。它不返回承诺,也不应该与一个承诺一起使用
标签: javascript jquery return-value when-js