gpt4 book ai didi

javascript - 如何检测一个功能何时从另一个功能完成?

转载 作者:行者123 更新时间:2023-11-30 08:17:05 26 4
gpt4 key购买 nike

我有一个正在构建的 javascript 函数,用于为 div 的折叠设置动画,然后继续执行其他工作。代码如下:

function newsFeed() {

var self = this;

this.collapse = function(listingID,orig_height,curr_height,opacity) {

var listing = document.getElementById(listingID);
var reduceBy = 5;
if(curr_height > reduceBy) {
curr_height = curr_height-reduceBy;
listing.style.overflow = "hidden";
listing.style.height = (curr_height-40) + "px";

if(opacity > 0) {
opacity = opacity - 10;
var opaque = (opacity / 100);

listing.style.opacity=opaque;
listing.style.MozOpacity=opaque;
listing.style.filter='alpha(opacity='+opacity+')';
}

setTimeout(function() { self.collapse(listingID,orig_height,curr_height,opacity); },1);

}else{

return true;

}
}

this.remove = function(listingID) {

var listing = document.getElementById(listingID);
var currHeight = listing.offsetHeight;

if (this.collapse(listingID,currHeight,currHeight,100)) {

// DO SOME OTHER STUFF

}

}

}

var newsFeed = new newsFeed();
newsFeed.remove('closeMe');

我无法让 this.remove 函数等待 this.collapse 完成并返回 true。这不可能吗?继续下去的最佳方式是什么?

重要提示:我希望能够将 this.collapse 与其他功能一起使用,这些功能尚未以与我在这里相同的方式构建。

最佳答案

I cannot get the this.remove function to wait while this.collapse finishes

没错,这是不可能的。在 JavaScript 中,只有一个执行流程。当浏览器调用您的代码时,您可以进行一些处理,但对于进一步发生的任何事情(超时或事件调用),您必须将控制权返回给浏览器。

像collapse()这样的“异步”过程是通过设置超时来完成的,因此必须多次将控制权返回给浏览器;当 remove() 第一次调用 collapse() 时,它会在第一次超时设置后立即返回;在 remove() 本身返回之前无法触发该超时,因此只有在第一次调用 collapse() 是动画的最后一帧(即元素已经为 5px 或更小)时,您的“if”代码才会执行​​。否则 collapse() 的“return true”将只返回 true 给浏览器的超时调用者,它根本不关心你返回给它的值是什么。

有些语言为您提供了线程或协程等工具,可以让异步例程从同步例程运行; JavaScript 没有。相反,remove() 必须为 collapse() 提供一个回调函数,它可以在最后一帧调用自己。

关于javascript - 如何检测一个功能何时从另一个功能完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1370766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com