Reset setTimeout after a period of time - javascript

Struggling to workout where 'clearTimeout' would fit in to this flow:
$(window).ready(function() {
setTimeout(function() {
$('.hoverone').addClass('flip');
}, 2000);
setTimeout(function() {
$('.hovertwo').addClass('flip');
}, 2500);
setTimeout(function() {
$('.hoverone').removeClass('flip');
}, 4000);
setTimeout(function() {
$('.hovertwo').removeClass('flip');
}, 4500);
});
Once the last action has been made - I would like the timer to reset and the flow to begin again. I tried clearTimeout but I have a very specific flow of timed actions I need to complete.

I suggest you use wrap all your set timeouts in a function. This way you dont need to clear the timeout.
var intervalFunction = function(){
setTimeout(function() {
$('.hoverone').addClass('flip');
}, 2000);
setTimeout(function() {
$('.hovertwo').addClass('flip');
}, 2500);
setTimeout(function() {
$('.hoverone').removeClass('flip');
}, 4000);
setTimeout(function() {
$('.hovertwo').removeClass('flip');
intervalFunction();
}, 4500);
}
$(window).ready(intervalFunction);

Here's the Answer for anyone else looking - thanks to Mike
$(window).ready(function flow(){
setTimeout(function() {
$('.hoverone').addClass('flip');
},
2000);
setTimeout(function() {
$('.hovertwo').addClass('flip');
},
2500);
setTimeout(function() {
$('.hoverone').removeClass('flip');
},
4000);
setTimeout(function() {
$('.hovertwo').removeClass('flip');
},
4500);
setInterval( flow, 8000 );
});

I would try something like this:
$(window).ready(function() {
//all setTimeouts start (almost) the same time
var time1 = 2000,
time2 = time1 + 500,
time3 = time2 + 1500,
time4 = time3 + 500,
repeatTime = time4 + 1000; //delay before the restart
//this will run again and again until you stop it
//basically it will start over after 1 second after the 4th settimeout is finished
var Fn = setInterval(function() {
setTimeout(function() {
$('.hoverone').addClass('flip');
}, time1);
setTimeout(function() {
$('.hovertwo').addClass('flip');
}, time2);
setTimeout(function() {
$('.hoverone').removeClass('flip');
}, time3);
setTimeout(function() {
$('.hovertwo').removeClass('flip');
}, time4);
}, repeatTime);
//this is how you stop it from repeating anymore
//clearInterval(Fn);
});
I think this is self-explanatory, but feel free to question further.

JsFiddle
$(window).ready(function(){
var hoverone,hovertwo;
call();
function call(){
hoverone= setTimeout(function() {
$('.hoverone').addClass('flip');
clearTimeout(hovertwo);
call1();
},
2000);
}
function call1(){
hovertwo = setTimeout(function() {
$('.hovertwo').addClass('flip');
clearTimeout(hoverone);
call2();
}, 2500);
}
function call2(){
hovertwo = setTimeout(function() {
$('.hoverone').removeClass('flip');
clearTimeout(hoverone);
call3();
}, 2500);
}
function call3(){
hovertwo = setTimeout(function() {
$('.hovertwo').removeClass('flip');
clearTimeout(hoverone);
call();
}, 2500);
}
});

To repeat these time events, you should use setInterval. Also, you can combine the four actions in one function:
$(window).ready(function(){
var halfSeconds = 0;
var timer = setInterval(function() {
halfSeconds = (halfSeconds + 1) % 12; // change the 12 to adjust repeat-delay
if (halfSeconds === 4) $('.hoverone').addClass('flip');
if (halfSeconds === 5) $('.hovertwo').addClass('flip');
if (halfSeconds === 8) $('.hoverone').removeClass('flip');
if (halfSeconds === 9) $('.hovertwo').removeClass('flip');
},
500);
// Optional: if you have an event that should stop the repetition:
$('#myStopButton').click(function() {
clearInterval(timer);
});
});
It will also be useful to keep the return value from setInterval so you can stop the animation when some event occurs (like a click on a "stop" button).

Related

Check if a specific class exist(button)

Got a problem with my function I have no idea how to make it work. Without if it works but spams in console. This function check if a multiple div class('open button') exist and do the code
(function() {
function openbutton() {
var button = setInterval(function() {
if (getEBCN('open button').length > 0) {
setTimeout(function() {
document.getElementsByClassName("open button")[0].click();
}, 1000);
setTimeout(function() {
document.getElementsByClassName("button 2")[0].click();
}, 1500);
setTimeout(function() {
document.getElementsByClassName("button close")[0].click();
}, 18000);
}
else {
clearInterval(button);
}
}, 16000);
}
})();
simply do
const existFlag = document.getElementsByClassName('someClassName').length > 0;
setInterval(function(){
const existFlag = document.getElementsByClassName('sampleClass').length > 0;
console.log(existFlag)
}, 3000);
getEBCN is not a method in JavaScript (unless you have defined it). You need to change
getEBCN('open button').length > 0
to
document.getElementsByClassName('open button').length > 0
Well that works #user3003238. This do rly what i wanted.
(function() {
setInterval(function(){
const existFlag = document.getElementsByClassName('open button').length > 0;
console.log(existFlag);
if (existFlag == true)
{
setTimeout(function() {document.getElementsByClassName("open button")[0].click();}, 1000);
setTimeout(function() {document.getElementsByClassName("button 2")[0].click();}, 1500);
setTimeout(function() {document.getElementsByClassName("button close")[0].click();}, 18000);
}
else
{
clearInterval();
}
}, 20000);
})();

Scripts crashing each other

well my problem is hopefully easy: 3 actions that shall happen while hovering a photo. The timer at the bottom works now, the other things crashed. A Page shall open in 5 seconds and the photo shall move out of the display before. Sounds easy, doesnt it? I hope so.
Do you guys know what I can do?
Thanks already and best regards!
<script>
var interval;
var timer = 5;
$('.HoverBalken').on({'mouseover': function () {
timer = setTimeout(function () {
$('.HoverBalken').toggleClass('HoverBalken-active');
$('.N').toggleClass('N-active');
$('.K').toggleClass('K-active');
}, );
timer = setTimeout(function () {
window.location = "FoliagePlates.html"
}, 5000);
}, 'mouseover': function () {
interval = setInterval(function() {
timer--;
$('.timer').text(timer);
if (timer === 0) clearInterval(interval);
}, 1000);
}, 'mouseout' : function () {
clearTimeout(timer);
$('.HoverBalken').removeClass('HoverBalken-active');
$('.N').removeClass('N-active');
$('.K').removeClass('K-active');
clearInterval(interval);
timer = 5;
$('.timer').text(timer);
}
});
</script>
<script>
var interval;
var timer = 5;
var timeout1,timeout2;
$('.HoverBalken')
.mouseover(function() {
//use different variable than your timer
timeout1 = setTimeout(function () {
$('.HoverBalken').toggleClass('HoverBalken-active');
$('.N').toggleClass('N-active');
$('.K').toggleClass('K-active');
}, 2000); //forgot time here
//use different variable than your timer and first timeout
timeout2 = setTimeout(function () {
window.location = "FoliagePlates.html"
}, 5000);
//stay in same scope, don't define event again
interval = setInterval(function() {
timer--;
$('.timer').text(timer);
if (timer === 0) clearInterval(interval);
}, 1000);
})
.mouseout(function() {
//clear both timers
clearTimeout(timeout1);
clearTimeout(timeout2);
$('.HoverBalken').removeClass('HoverBalken-active');
$('.N').removeClass('N-active');
$('.K').removeClass('K-active');
clearInterval(interval);
timer = 5;
$('.timer').text(timer);
});
</script>
this should fix it, notice the comments in code

Javascript, run function for 0.5 seconds then stop (Loop)

I'm running a node server with raspberry pi gpio modules installed. I'm trying to get my ESC to start and run for 0.5 seconds, then I need it to stop for .5 second, then start again in a loop. however if "start" = 0 (Button off) I need the loop to stop completely and set the servo pulse width to 1000 (Motor Stop)
Here is my code, It kinda works. But doesn't stop
var start = new blynk.VirtualPin(4);
start.on('write', function t(start) {
if (start == 1) {
setInterval(function() {
setInterval(function() {
motor.servoWrite(1920);
}, 500);
setInterval(function() {
motor.servoWrite(1000);
}, 1000);
}, 500);
} else {
motor.servoWrite(1000);
}
motor.servoWrite(1000);
});
Could someone show me where I've gone wrong?
Store your interval in a variable
var myInterval = setInterval(function() { [... your code code] },delay);
then to stop it by
clearInterval(myInterval);
var start = new blynk.VirtualPin(4);
motor.servoWrite(1000);
var interval, timeout;
start.on('write', function t(start) {
if (start == 1) {
clearInterval(interval);
clearTimeout(timeout);
interval = setInterval(function() {
motor.servoWrite(1920);
timeout = setTimeout(function() {
motor.servoWrite(1000);
}, 500);
}, 1000);
} else {
clearInterval(interval);
clearTimeout(timeout);
motor.servoWrite(1000);
}
});
I think setInterval might be the wrong thing to use. The setInterval is reoccurring. Where you really just want to run something once, wait, then run something else. Try doing it with setTimeout, it waits for x ms then executes something.
var id = null;
start.on('write', function t(start) {
if(start == 1){
pulse();
}
else {
clearTimeout(id);
motor.servoWrite(1000);
}
});
function pulse() {
servoOn();
id = setTimeout(function(){
servoOff();
id = setTimeout(function(){
pulse();
}, 1000);
}, 500);
}
function servoOn(){
motor.servoWrite(1920);
}
function servoOff(){
motor.servoWrite(1000);
}

Run function once then disallow further calls for 5 seconds

I want to stop a function being fired again for 5 seconds after the last.
This is what I had:
return {
buildUI: function() {
el.nav.on({
mouseenter: function() {
el.logo.addClass('spin');
},
mouseleave: function() {
el.logo.removeClass('spin');
}
});
}
}
On mouseenter, add class to spin the logo. On mouseleave, remove the class. But to stop the logo spinning every mouseenter, I want to add a 5 second ban since the last.
This is what I tried, amongst other attempts:
var flipLogoTimer;
return {
el.nav.on({
mouseenter: function() {
if (!flipLogoTimer) {
el.logo.removeClass('spin').addClass('spin');
}
},
mouseleave: function() {
el.logo.removeClass('spin');
flipLogoTimer = setTimeout(function() {
//
}, 5000);
}
});
}
I tried to add a 5 second timer to the mouseleave event, so the next mouseenter can check if the timer is still running to determine whether or not to run the animation again.
Where am I going wrong and is there a better way? It's a difficult one to search for, as there are so many questions about running a function on a timer.
You can use the flag like
return {
buildUI: function () {
var flag = false;
el.nav.on({
mouseenter: function () {
if (flag) {
return;
}
el.logo.addClass('spin');
},
mouseleave: function () {
if (flag) {
return;
}
flag = true;
el.logo.removeClass('spin');
setTimeout(function () {
flag = false;
}, 5000)
}
});
}
}
You can try something like this by toggling value of flipLogoTimer
var flipLogoTimer=false;
return {
el.nav.on({
mouseenter: function() {
if (!flipLogoTimer) {
el.logo.removeClass('spin').addClass('spin');
}
},
mouseleave: function() {
el.logo.removeClass('spin');
flipLogoTimer=true;
setTimeout(function() {
flipLogoTimer=false;
}, 5000);
}
});
}
You can use timestamp. Idea: you fix last time when you added/removed class, and compare it with current date.
// 5000 - equal to 5 seconds
function checkTimestamp(a, b){
return Math.abs(a - b) < 5000;
}
return {
buildUI: function () {
var lastTimeStamp = null;
el.nav.on({
mouseenter: function () {
if(lastTimeStamp && checkTimestamp(lastTimeStamp, Date.now())
return false;
el.logo.addClass('spin');
lastTimeStamp = Date.now();
},
mouseleave: function () {
if(lastTimeStamp && checkTimestamp(lastTimeStamp, Date.now())
return false;
el.logo.removeClass('spin');
lastTimeStamp = Date.now();
}
});
}
}

setTimeout with jQuery.hover() overlapping

I've got an effect I want triggered one second after page load, then subsequently every 3 seconds (on repeat). When the user hovers over an element (#hover), the effect pauses (temporarily). When they stop hovering over it, the effect resumes after 2 seconds.
I'm having a lot of trouble with overlapping sounds and animations, particularly when I hover and then unhover over the element quickly. What's wrong with my code? (Fiddle)
var test;
function hoverTest(arg) {
if (arg == 'stop') {
clearTimeout(test);
}
if (arg == 'start') {
playSound();
$('#hover').transition({
opacity: 0,
duration: 1000,
complete: function() {
$('#hover').transition({
opacity: 1,
duration: 1000,
complete: function() {
test = setTimeout(function() { hoverTest('start'); }, 3000);
}
});
}
});
}
}
$('#hover').hover(function() {
hoverTest('stop');
}, function() {
setTimeout(function() {
hoverTest('start');
}, 2000);
});
function playSound() {
var sound = new Audio('sound.mp3');
sound.play();
}
setTimeout(function() {
hoverTest('start');
}, 1000);
copy paste this in a file and run that html file.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<style>
#hover {
width: 100px;
height: 100px;
background: red;
}
</style>
<div id="hover"></div>
<script type="text/javascript">
var interval = null;
var hoverTest = function(method){
playSound();
$("#hover").fadeOut(1000, function() {
$(this).fadeIn(1000);
});
}
var playSound =function() {
var sound = new Audio('http://www.sounddogs.com/previews/25/mp3/306470_SOUNDDOGS__an.mp3');
sound.play();
}
$(document).ready(function(){
interval = setInterval('hoverTest()',3000);
$("#hover").mouseenter(function(){
clearInterval(interval);
}).mouseleave(function(){
interval = setInterval('hoverTest()',3000);
})
})
</script>
Try adding "clearTimeout(test);" the first thing in the hoverTest function.
eg:
var test;
function hoverTest(arg) {
clearTimeout(test);
if (arg == 'stop') {
clearTimeout(test);
}
if (arg == 'start') {
playSound();
$('#hover').transition({
opacity: 0,
duration: 1000,
complete: function() {
$('#hover').transition({
opacity: 1,
duration: 1000,
complete: function() {
test = setTimeout(function() { hoverTest('start'); }, 3000);
}
});
}
});
}
}
Try this: (clear the timer before starting)
$('#hover').hover(function() {
hoverTest('stop');
}, function() {
clearTimeout(test);
setTimeout(function() {
hoverTest('start');
}, 2000);
});

Categories

Resources