Search code examples
jqueryhtmlcleartimeout

Create a setTimeout cancel button


I have a text fadeIn/fadeOut script that on click displays a designated image for a number of seconds defined with setTimeout.

I want to create a Cancel button for when i don't want to see that image for the entire set time.

I tried adding a clearTimeout function to a class="cancel" and point it to a but couldn't make it work...

jsFiddle

My html:

<div id="help">
<p class="helper" data-timeout-value="5000" id="1">Do you...?</p>
<p class="helper" data-timeout-value="7000" id="2">Do you still...?</p>
<p class="helper" data-timeout-value="8000" id="3">Do you really still...?</p>
</div>

<div id="image1"></div>
<div id="image2"></div>
<div id="image3"></div> 

Script

var myTime;
$(".helper").click(function(){
   var $this = $(this),
       $id = $this.attr('id'),
       $timeout = $this.attr('data-timeout-value');

   $("#help").fadeOut(500);
   $("#image"+$id).fadeIn(500);

   myTime = setTimeout(function() {
      $('#image'+$id).fadeOut(500);
      $("#help").fadeIn(500);
   }, $timeout);
})

$('div.cancel').click(function(){
        clearTimeout(myTime);

});

Solution

  • You seem to be complicating things, just use jQuery's animations and delay, and stop them when the cancel button is clicked

    var helper = $(".helper");
    var helperIndex = -1;
    
    (function showNextHelp() {
        ++helperIndex;
        helper.eq(helperIndex % helper.length)
              .fadeIn(500)
              .delay(1000)
              .fadeOut(500, showNextHelp);
    })();
    
    helper.on('click', function(){
       $("#help").fadeOut(500);
       $("#image" + this.id).addClass('active')
                            .fadeIn(500)
                            .delay($(this).data('timeout-value'))
                            .queue(function(next) {
                                $(this).fadeOut(500, function() {
                                    $(this).removeClass('active');
                                });
                                $("#help").fadeIn(500);
                                next();
                            });
    });
    
    $('.cancel').click(function(){
        $('.active').stop(true, true).hide(); // use fadeOut / In for animations
        $("#help").stop(true, true).show();
    });
    

    FIDDLE