clearInterval不起作用(或者可能是setTimeout)

时间:2014-08-19 15:27:43

标签: javascript jquery web settimeout clearinterval

脚本的想法是在按下按钮后禁用按钮1500ms。按下按钮激活“加载栏”的动画。 1500ms后脚本应该再次运行。 问题是只有setTimeout方法不起作用。动画效果很好,然后按钮被禁用,但在1500ms后它不会启用 感谢任何帮助。

$(document).ready(function() {
    $('button').click(function(){                                  // <-- works fine 
        var width = Math.floor(Math.random() * (231 - 23) + 23);   // <-- works fine 
        $('.bar div').animate({width: width}, 1500);               // <-- works fine 
        $('.bar div span').text(Math.floor((width*100)/230) + '%');// <-- works fine 

        var intervalID = setInterval(function() {                  // <-- works fine 
            $('button').prop('disabled', true)}, 50);              // <-- works fine 
        setTimeout (function() {              // <-- this doesn't work
           clearInterval(intervalID)}, 1500); // <-- this doesn't work
    });
});

1 个答案:

答案 0 :(得分:1)

不需要间隔。您只需要禁用该按钮,设置超时功能并重新启用该按钮。类似的东西:

$("button").on("click", function(e) {
    var btn = $(this);

    var width = Math.floor(Math.random() * (231 - 23) + 23);
    $('.bar div').animate({width: width}, 1500);
    $('.bar div span').text(Math.floor((width*100)/230) + '%');

    btn.prop('disabled', true);
    setTimeout(function() {
        btn.prop('disabled', false);
    }, 1500);
});

这是JSFiddle

相关问题