Blog Easily Cancel setTimeout() Function Through Variable
June 16, 2014 Development, jQuery Social Share
The event related to a custom slider and if the call to action button was clicked, I wanted to pause the slider for a moment to give the user enough time to take in the new content.
I found my solution via mck89 at Stack Overflow who declared the setTimeout() function in a variable that could then be destroyed.
timer = setTimeout(
function()
{
$('.caption').fadeOut(750);
}, 6000);
When the call to action button is clicked, the extra content fades in and the slider is paused. Afterwards, I canceled the timer variable and the fade out function, declared above.
I then created another setTimeout function to resume the slider and fade out the container to continue the process. You can see I set this new setTimeout() function for 8 seconds to give the user extra time to read the newly revealed content.
$(document).on('click', '.openme', function()
{
$('.caption .popup').fadeIn(750);
$('body').data('backstretch').pause();
clearTimeout(timer);
setTimeout(
function()
{
$('body').data('backstretch').resume();
$('.caption').fadeOut(750);
}, 8000);
return false;
});
The “backstretch” of the above code refers to the Backstretch jQuery plugin which is great for background images.