For the life of me I can't figure out how to clear timeouts in an array if they exist.
I have a single page app(SPA) website(http://www.rock3t.ca/) and the ID's grow every time you click "Home" very fast, which doesn't seem to cancel the timeouts. Visit the site and you will see the slogan under the logo in the center changing at a very fast pace and then slowing down. Click on "Home" multiple times quick to see how it reacts. It hasn't cleared, you will notice blips.
//slogans
function loadSlogans(){
//slogan timeouts
var sloganTimeouts = [];
//slogans
var slogans = ['Websites', 'Apps', 'Media', 'Code', 'SEO', 'CRM','Ads','Flyers','Logos','Games','Streams','Web','Websites', 'Apps', 'Media', 'Code', 'SEO', 'CRM','Ads','Flyers','Logos','Games','Streams','Web'];
var sloganTime = 100;
var sloganTimeFade = 0;
var slogans_length = slogans.length;
var sloganHalfTime = slogans_length / 2;
//clear slogan timeouts
$(slogans).each(function(i){
//clear timeout if exists
if(typeof sloganTimeouts[i] !== "undefined"){
clearTimeout(sloganTimeouts[i]);
}
});
//slogan timeout
function runSloganTimeout(i) {
//easing out time when half way
if(i > sloganHalfTime){
sloganTimeFade++;
sloganTime = (i * 100) + (sloganTimeFade * 100) * (sloganTimeFade / 4);
}else{
sloganTime = i * 100;
}
//set timeouts
sloganTimeouts[i] = setTimeout(function(){
//append slogans
$('#slogan span').html(slogans[i]);
},sloganTime);
}
//each slogan
$(slogans).each(function(i){
//run
runSloganTimeout(i);
});
}
Thanks
It has cleared, but previous process hasn't over, so you will not clear all upcoming timeouts. One of the solutions: add processId global var and interrupt the previous process. See my example: Plunker
var processId = 0;
//slogans
function loadSlogans(){
processId++;
var selfProcessId = processId;
//slogan timeouts
...
//slogans
...
//clear slogan timeouts
...
//slogan timeout
function runSloganTimeout(i) {
//easing out time when half way
...
//set timeouts
sloganTimeouts[i] = setTimeout(function(){
//append slogans
if( selfProcessId == processId )
$('#slogan span').html(i+slogans[i]);
},sloganTime);
}
//each slogan
$(slogans).each(function(i){
//run
if( selfProcessId == processId )
runSloganTimeout(i);
});
}