Reputation: 2290
Will try to explain what I'm trying to do here. I have 2 logos and i want toggle 1 class after every setTimeout function "show"
For some reason resetting the timeOut is not working properly.
The first function is fired after 5 seconds and the second function is fired after 8 seconds. I want to reset these because I don't want the function to be fired before the correct "X" amount of seconds is done.
let logo1 = document.querySelector('.logo-1');
let logo2 = document.querySelector('.logo-2');
function firstLogo() {
console.log('First logo');
logo1.classList.add('show');
logo2.classList.remove('show');
setTimeout(firstLogo, 5000);
}
function secondLogo() {
console.log('Second logo');
logo1.classList.remove('show');
logo2.classList.add('show');
setTimeout(secondLogo, 8000);
}
setTimeout(firstLogo, 8000);
setTimeout(secondLogo, 5000);
Can someone help?
Upvotes: 0
Views: 38
Reputation: 147513
You will get some strange interactions between the timeouts, e.g.
Perhaps you want logo 2 shown for 5 seconds, then logo 1 for 3 seconds, then logo 2 for 5 seconds, etc.
In that case, you can call one function from the other, using appropriate settings for setTimeout. Since the default is to display the logos, I've changed show to hide, e.g.
let logo1 = document.querySelector('.logo-1');
let logo2 = document.querySelector('.logo-2');
function firstLogo() {
console.log('Hiding first logo');
logo1.classList.toggle('hide');
logo2.classList.toggle('hide');
setTimeout(secondLogo, 3000);
}
function secondLogo() {
console.log('Hiding second logo');
logo1.classList.toggle('hide');
logo2.classList.toggle('hide');
setTimeout(firstLogo, 5000);
}
firstLogo();
.hide {
display: none;
}
<span class="logo-1">logo 1</span><span class="logo-2 hide">logo 2</span>
Upvotes: -1
Reputation: 187
You can use something like this:
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
The clearTimeout
will prevent the function set with the setTimeout() to execute.
Hope this helps.
Upvotes: 2