I have multiple setTimeout functions like this:
function bigtomedium(visiblespan) { visiblespan.removeClass('big').addClass('medium'); setTimeout(function(){ mediumtosmall(visiblespan);},150); }; function mediumtosmall(visiblespan) { visiblespan.removeClass('medium').addClass('small'); setTimeout(function() { smalltomedium(visiblespan); },150); }; function smalltomedium(visiblespan) { visiblespan.removeClass('small').addClass('medium'); setTimeout(function() { mediumtobig(visiblespan); },150); }; function mediumtobig(visiblespan) { visiblespan.removeClass('medium').addClass('big'); setTimeout(function() { bigtomedium(visiblespan); },150); };
Which is activated in jquery onclick:
$('div.click').click( function(event) { var visiblespan = $('span:visible'); mediumtosmall(visiblespan); } );
What I need to do, is to get the click to hide invisible span as well.
$('div.click').click( function(event) { var visiblespan = $('span:visible'); var invisiblespan = $('span:not(:visible)'); mediumtosmall(visiblespan); clearTimeout(invisiblespan); } );
What I’m not sure how to do is to write the clearTimeout function that will stop the loop. Any help is greatly appreciated. Thanks.
Not sure if you are already aware of this but, clearTimeout accepts a timeoutID that is previously returned from a call to setTimeout.
Therefore you need to assign this timeout id to a variable that remains in scope for when you need to cancel it. Then pass it to the clearTimeout call when you need to stop the loop.
As it is just an integer id, another option might be to create a custom attribute on a dom element using something like ‘domElement.setAttribute(‘timoutIDFirst’);’ (or attr in jQuery) and then just retrieve it using getAttribute when required.
Considering you have multiple timers, using custom attributes on the DOM elements may help keep things tidier.
EG:
and then: