function One(){
setTimeout(function(){
Two();
},3000);
}
function Two(){
setTimeout(function(){
One();
},3000);
}
function Stop(){
alert('this should run,and the functions above should stop');
}
I want to stop autorun of the first two functions,when you click on the third.
By now,if you click on the third,the alert shows up,but then the loop continue.Any way of doing this?
var oneTimeout, twoTimeout;
function One(){
oneTimeout = setTimeout(function(){
Two();
},3000);
}
function Two(){
twoTimeout = setTimeout(function(){
One();
},3000);
}
function Stop(){
clearTimeout(oneTimeout);
clearTimeout(twoTimeout);
alert('this should run,and the functions above should stop');
}
If you store the ID of the timeout call you can clear it at any time.
var timeoutId1, timeoutId2;
function One() {
timeoutId1 = setTimeout(function() {
Two();
}, 3000);
}
function Two() {
timeoutId2 = setTimeout(function() {
One();
}, 3000);
}
function Stop() {
// alert('this should run,and the functions above should stop');
clearTimeout(timeoutId1);
clearTimeout(timeoutId2);
}
Something like this :
function TimerController(){
var ids = {};
this.start = function(id, time, fn) {
if (ids[id]) clearTimeout(ids[id]);
ids[id] = setTimeout(function(){
fn();
delete ids[id];
}, time);
}
this.stop = function(id) {
clearTimeout(ids[id]);
delete ids[id];
}
this.stopAll = function() {
for (var id in ids) this.stop(id);
}
}
var ctrlr = new TimerController();
function One(){
ctrlr.start('one', 3000, Two);
}
function Two(){
ctrlr.start('two', 3000, One);
}
function Stop() {
ctrlr.stopAll();
}
Little explanation:
timeouts and intervals in javascript both return identifier, that can be used for event cancelling.
var id = setTimeout(function(){console.log('Triggered!');}, 0);
clearTimeout(id);
Function will never been called in the example above.
So, we should store timeout ids, if we want to be able to stop it.
TimerController above incapsulate this logic.
You should use var timer = setTimeout(function()...); return timer; in your first two function and pass the two timer variable (which holds a number identifying the timeout timer) to the third function. Then just call clearTimeout(timer) when the third function gets called.
Check out this MDN docs for timeout
var timeout1;
//... Define Function name
function rotate() {
timeout1 = setTimeout( rotate, 4000);
}
Another way
var rotateTimeout;
rotateTimeout = window.setInterval(rotate,4000);
window.clearInterval(rotateTimeout);
Related
I have a function like this :
$.SetInLocalStorageVideoTime = function (uuid) {
alert(uuid);
var Interval = setInterval(function () {
localStorage.setItem('poption-ctime-'+ uuid , jwplayer("target").getPosition());
},10000);
var ClearInterVal = clearInterval(Interval);
return {
Interval : Interval,
ClearInterVal : ClearInterVal
}
};
My problem is how to call the Interval function and pass uuid param to that.
I have tried $.SetInLocalStorageVideoTime("blahblah").Interval(); but it throws an error.
var Interval = setInterval(...)
This immediately calls the setInterval function and assigns its return value to Interval; same for clearInterval. You don't want to call the function, you want to create a function which when called calls the function. Two ways to do that:
var Interval = function () {
setInterval(...);
}
var Interval = setInterval.bind(null, ...);
Putting it all together, you want this:
$.SetInLocalStorageVideoTime = function (uuid) {
var interval = null;
var set = function () {
interval = setInterval(function () {
localStorage.setItem('poption-ctime-'+ uuid , jwplayer("target").getPosition());
}, 10000);
};
var clear = function () {
clearInterval(interval);
};
return {
Interval : set,
ClearInterVal : clear
}
};
Look this plunker : https://plnkr.co/edit/7H61Vv6m8M552CNeIpSA?p=preview
You must encapsulate into function :
var stop;
var interval = function () {
stop = setInterval(function () {
console.log(uuid);
},100);
}
var ClearInterVal = function () { clearInterval(stop) };
You have several simple issues, you must export function that will clearTimeout
$.SetInLocalStorageVideoTime = function(uuid) {
// auto start interval, you could
// add starter function or something
var Interval = setInterval(function() {
localStorage.setItem('poption-ctime-' + uuid, jwplayer("target").getPosition());
}, 10000);
// clear function
// exported
var ClearInterVal = function() {
if (Interval)
clearInterval(Interval);
}
return {
// Interval is not required here
ClearInterVal: ClearInterVal
}
};
$.SetInLocalStorageVideoTime();
I saw the snippet below that validates an input field after every user change, but it waits for 1, 5 seconds of user inactivity before it actuallyt starts validating:
var timer;
var inputElement = document.getElementById("nameInput");
inputElement.oninput = function()
{
delayedInputValidation(validateInput, 1500);
};
function delayedInputValidation(func, delayInMilliseconds)
{
clearTimeout(timer);
timer = setTimeout(func, delayInMilliseconds);
}
function validateInput()
{
... //stuff here
}
My questions is not about input validation, but about the timeout mechanism. I tried to generalize the delay function to make it work for arbitrary functions:
function delayedFunction(timer, func,delayInMilliseconds)
{
clearTimeout(timer);
timer = setTimeout(func, delayInMilliseconds);
}
The point is that you have several timers in your JavaScript, for example:
var inputTimer;
var otherTimer;
...
And if you pass along the same timer, the delay function woul clear (reset) the correct timer and then set it again using the setTimeout function.
However, this doesn't work because the timer object is passed in a reference-by-value way (discussion here), resulting in the local variable timer to be changed, but not the actual inputTimer.
How can I fix this method?
You can use something like
var timers = {};
function delayedFunction(timer, func, delayInMilliseconds) {
clearTimeout(timers[timer]);
timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction('inputTimer', func1, delay1);
delayedFunction('otherTimer', func2, delay2);
Or like this:
var timers = [],
inputTimer = 0,
otherTimer = 1;
function delayedFunction(timer, func, delayInMilliseconds) {
clearTimeout(timers[timer]);
timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction(inputTimer, func1, delay1);
delayedFunction(otherTimer, func2, delay2);
I have this code:
var int1 = setInterval(function () {
// do stuff
if(//stuff done){
clearInterval(int1);
setTimeout(
function () {
setInterval(int1)
}
,60000);
}}
}, 1000)
and want the interval to be running again after 60 seconds but setInterval(int1) doesn't seem to trigger it again. What am I doing wrong?
EDIT: full code: http://pastie.org/8704786
That'd because int1 is not a function, but an interval id. Try this instead:
var int1;
var func = function () {
// do stuff
if(//stuff done){
clearInterval(int1);
setTimeout(func, 60000);
}
};
int1 = setInterval(func, 1000);
You did 2 mistakes:
setInterval whant a function, while int1 contains an interval handle
You didn't pass amount of time in your setInterval call
What you want probably is:
var int1;
function scheduleStuff() {
int1 = setInterval(doStuff, 1000);
}
function doStuff() {
// do stuff
if(/*stuff done*/){
clearInterval(int1);
setTimeout(scheduleStuff,60000);
}}
}
scheduleStuff();
set intervall expectes a function wich is called after waiting time...
this line is wrong:
setInterval(int1)
no function and no waiting time given...
I'm trying to stop/clear the interval but i'm getting an error.
code below:
function play(){
function sequencePlayMode() {
var arg1;//some arguments
var arg2;//some arguments
changeBG(arg1,arg2);//here is function that changes the background
}
var time = 5000;
var timer = setInterval(sequencePlayMode, time);//this starts the interval and animation
}
function stop(){
var stopPlay = clearInterval(sequencePlayMode);//here i'm getting error "sequencePlayMode is not defined"
}
$("#startAnimation").click(function(){
play();
});
$("#stopAnimation").click(function(){
stop();
});
Can someone help me with this please?
You need to use the variable that you store the function in and not the function that you call it. You also need to make the variable accessible to the other function.
(function () {
var timer; //define timer outside of function so play and stop can both use it
function play(){
function sequencePlayMode() {
var arg1;//some arguments
var arg2;//some arguments
changeBG(arg1,arg2);//here is function that changes the background
}
var time = 5000;
timer = setInterval(sequencePlayMode, time);//this starts the interval and animation
}
function stop(){
var stopPlay = clearInterval(timer);
}
$("#startAnimation").click(function(){
play();
});
$("#stopAnimation").click(function(){
stop();
});
})();
I have a setInterval loop. It's set to 3500 milliseconds, like so:-
var loop = setInterval(function() { /*stuff*/ }, 3500);
At one point in 'stuff' if a certain situation occurs, I want to force a new iteration of the loop and NOT WAIT for the 3500 milliseconds. How is that possible? Is it continue or do I just need to frame the process differently?
You could try writing an anonymous self-calling function using setTimeout instead of setInterval:
var i = 0;
(function() {
// stuff
i++;
if (i % 2 == 0) {
// If some condition occurs inside the function, then call itself once again
// immediately
arguments.callee();
} else {
// otherwise call itself in 3 and a half seconds
window.setTimeout(arguments.callee, 3500);
}
})(); // <-- call-itself immediately to start the iteration
UPDATE:
Due to a disagreement expressed in the comments section against the usage of arguments.callee, here's how the same could be achieved using a named function:
var i = 0;
var doStuff = function() {
// stuff
i++;
if (i % 2 == 0) {
// If some condition occurs inside the function, then call itself once again
// immediately
doStuff();
} else {
// otherwise call itself in 3 and a half seconds
window.setTimeout(doStuff, 3500);
}
};
doStuff();
You can use something like this... using setTimeout instead of setInterval...
<script type="text/javascript">
var show;
var done = false;
show = setTimeout(showHideForm, 3500);
function showHideForm() {
// Do something
if(done) {
clearTimeout(show);
show = setTimeout(showHideForm, 2000);
}
}
</script>
clearTimeout takes as argument the handle which is returned by setTimeout.
Use a named function and call it when you want.
var loop = setInterval(loopFunc, 3500);
function loopFunc(){
//do something
}
function anticipate(){
clearInterval(loop); //Stop interval
loopFunc(); //Call your function
loop = setInterval(loopFunc, 3500); //Reset the interval if you want
}
My contrived example:
var time = 3500,
loops = 0,
loop;
(function run(){
var wait = time,
dontwait = false;
if (loops++ == 5) {
loops = 0;
dontwait = 1000;
}
console.log('Interval: ', dontwait || wait);
return loop = setTimeout(run, dontwait || wait);
})();
http://jsfiddle.net/NX43d/1/
Basically, a self-invoking function looping back on a self-calling function, with (!) shorthand variable switching. Nifty.
function looper(t) {
var loop = setInterval(function() {
document.write(s++);
if (mycondition) { // here is your condition
loopagain(200); // specify the time which new loop will do
loop = window.clearInterval(loop); // clear the first interval
return; // exit from this function!
}
}, t);
}
window.onload = looper(1000); // this will have default setInterval function time ans will start at window load!
function loopagain(t) {
looper(t);
}
http://jsfiddle.net/tFCZP/