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

时间:2017-02-22 11:16:52

标签: javascript jquery

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

var webpage = require('webpage');

page = webpage.create();

page.viewportSize = {width: 15,
              height: 45};
page.zoomFactor = 0.30;

page.open('http://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20160504-openssl?vs_f=Cisco%20Security%20Advisory&vs_cat=Security%20Intelligence&vs_type=RSS&vs_p=Multiple%20Vulnerabilities%20in%20OpenSSL%20Affecting%20Cisco%20Products:%20May%202016&vs_k=1', function(status) {
    console.log(status);

    page.clipRect = { left:0, top:0, width:295, height: 200};

    page.render('d:/test/github.png');

    //console.log(render);
    phantom.exit();
});

这里一旦我们点击(循环 - 下一个)元素,函数开始执行,假设控制器在函数中间,此时用户再次点击元素第二次,控制器再次从头开始功能没有完成,如何使第二次点击等到完成?

3 个答案:

答案 0 :(得分:0)

使用.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. 您最后提出的问题是,后续点击应该等待动画完成
  3. 这两者是相互排斥的

    这个答案将或多或少地对上次动画完成后按顺序处理的点击事件进行排队

答案 1 :(得分:0)

您只需设置一个标志即可。我选择了一个css类,因此您可以在禁用时设置按钮的样式。

如果.cycle-next是表单元素,您可以使用.prop("disabled", true),也可以使用数据集值.data("disabled", true)

$(".cycle-next").on('click',function(){
    var $this = $(this);
    if($this.hasClass("disabled")) return false;

    var contWidth = $(".container").width(); 
    var finalWidth = ((contWidth*.25)*-1)+(parseInt($(".inner").css("left"))); 
    var contWidthC = contWidth*-1;

    if(finalWidth === contWidthC){
        $this.addClass("disabled");
        $(".inner").animate({left:"0"},200,function(){
            $this.removeClass("disabled");
        });
    }
});

答案 2 :(得分:-1)

尝试在单击时使用AJAX调用以禁用该按钮,并且在AJAX调用成功时再次启用该按钮。这是一个一致的解决方案