gpt4 book ai didi

javascript - 如何阻止 javascript 函数调用直到完成

转载 作者:行者123 更新时间:2023-11-28 10:46:12 24 4
gpt4 key购买 nike

如何阻止点击事件调用函数直到该函数完成,我已经编写了这个函数:

$(".cycle-next").on('click',function(){
var contWidth = $(".container").width();
var finalWidth = ((contWidth*.25)*-1)+(parseInt($(".inner").css("left")));
var contWidthC = contWidth*-1;

if(finalWidth === contWidthC){
$(".inner").animate({left:"0"},200,function(){

});
}

});

这里一旦我们点击(cycle-next)元素,函数就开始执行,假设 Controller 在函数中间,此时用户再次点击该元素, Controller 再次从函数的开头开始执行功能没有完成,如何让第二次点击等到完成?

最佳答案

使用 .promise()$.when() (和 IIFE)应该可以解决问题

;(function() {
var p = $.when(); // initial "promise" to get things moving on the first click
$(".cycle-next").on('click',function(){
p = p.then(function() { // chain the promise
var $inner = $('.inner');
var contWidth = $(".container").width();
var finalWidth = ((contWidth * .25) * -1) + parseInt($(".inner").css("left"));
var contWidthC = contWidth * -1;

if (finalWidth === contWidthC) {
return $inner.animate({ left: "0" }, 200, function() {
// put logic to execute when the animation ends here, or remove this if not needed
}).promise(); // returns a promise that presumably resolves when animation completes
}
});
});
})();

说实话,重新阅读这个问题,

  1. 您首先说要阻止后续点击,
  2. 您在结束问题时表示后续点击应等待动画完成

两者是互斥的

此答案或多或少会将点击事件排队,以便在上一个动画完成后按顺序处理

关于javascript - 如何阻止 javascript 函数调用直到完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42389750/

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