Rache Riveto Rache Riveto - 3 months ago 19
Javascript Question

clearTimeout() is not working properly

Here is a JSFiddle example of the problem.

When I click the button everything fades as expected and returns in 3 seconds or until cliked. However, if I do not wait the 3 seconds but click it early and then quickly click the button it returns in less than 3 seconds.

EDIT: a better explanation of the problem:
In the JSFiddle, click the green button, click the open space to stop the fade, and then click the green button again (this all has to be done quickly). The elements fade back in way too quickly.

Thanks Katana314

var waiting;

function startNext() {
$(document).off('click');
window.clearTimeout(waiting);
$('#correctT, #correctP').fadeOut('fast', function() {
$('#button1, #button2, #button3, #button4, #title, #image, #ame').fadeIn('slow');


})

}
$('#button1, #button2, #button3, #button4').click(function(e) {


$('#button1, #button2, #button3, #button4, #title, #image, #ame').fadeOut('fast', function() {


$('#button1, #button2, #button3, #button4, #title, #image, #ame').hide();
$('#correctT, #correctP').fadeIn('fast');

$(document).click(startNext);

waiting = setTimeout(startNext, 2500);
});
});

Answer

https://jsfiddle.net/1dmjvon3/3/

take care of your timeout ids...

if(waiting!==null){
    window.clearTimeout(waiting);
    waiting = null;
}

also

if(waiting===null) waiting = setTimeout(startNext, 2500);
Comments