my problem is that I can not stop a timer.
I had this method to set a timeout from this forum.
It supposed to store the identifyer in the global variable.
By accident, I found out that it is still running after I hide "mydiv".
I also need to know now, if the recursive function creates multiple instances or just one for the timeouts. Because first I thought that it overwrites "var mytimer" everytime.
Now I am not so sure.
What would be a solid way to stop the timer??
var updatetimer= function () {
//do stuff
setTimeout(function (){updatetimer();}, 10000);
}//end function
//this should start and stop the timer
$("#mybutton").click(function(e) {
e.preventDefault();
if($('#mydiv').is(':visible')){
$('#mydiv').fadeOut('normal');
clearTimeout(updatetimer);
}else{
$('#mydiv').fadeIn('normal');
updatetimer();
}
});
thanks, Richard
I think that most people are getting at the reason why this isn't working, but I thought I would provide you with updated code. It is pretty much the same as yours, except that it assigns the timeout to a variable so that it can be cleared.
Also, the anonymous function in a setTimeout is great, if you want to run logic inline, change the value of 'this' inside the function, or pass parameters into a function. If you just want to call a function, it is sufficient to pass the name of the function as the first parameter.
var timer = null;
var updatetimer = function () {
//do stuff
// By the way, can just pass in the function name instead of an anonymous
// function unless if you want to pass parameters or change the value of 'this'
timer = setTimeout(updatetimer, 10000);
};
//this should start and stop the timer
$("#mybutton").click(function(e) {
e.preventDefault();
if($('#mydiv').is(':visible')){
$('#mydiv').fadeOut('normal');
clearTimeout(timer); // Since the timeout is assigned to a variable, we can successfully clear it now
} else{
$('#mydiv').fadeIn('normal');
updatetimer();
}
});
I think you misunderstand 'setTimeout' and 'clearTimeout'.
If you want to set a timer that you want to cancel later, do something like:
foo = setTimeout(function, time);
then call
clearTimeout(foo);
if you want to cancel that timer.
Hope this helps!
As written mytimer is a function which never has the value of a timeout identifier, therefore your clearTimeout statement will achieve nothing.
I don't see any recursion here at all, but you need to store the value setTimeout returns you, and if you need to pair this with multiple potential events you need to store it against a key value you can lookup - something like an element id perhaps?
This is a simple pseudocode for controlling and conditioning recursive setTimeout functions.
const myVar = setTimeout(function myIdentifier() {
// some code
if (condition) {
clearTimeout(myIdentifier)
} else {
setTimeout(myIdentifier, delay); //delay is a value in ms.
}
}, delay);
You can not stop all the functions that are created, intead of that convert the function to setInterval (represent the same logic that your recursive function) and stop it:
// recursive
var timer= function () {
// do stuff
setTimeout(function (){timer();}, 10000);
}
The same logic using setInterval:
// same logic executing stuff in 10 seconds loop
var timer = setInterval(function(){// do stuff}, 10000)
Stop it:
clearInterval(timer);
As noted above, the main reason why this code isn't working is that you're passingt he wrong thing into the clearTimeout call - you need to store the return value of the setTimeout call you make in updateFunction and pass this into clearTimeout, instead of the function reference itself.
As a second suggestion for improvement - whenever you have what you call a recursive timeout function, you would be better off using the setInterval method, which runs a function at regular intervals until cancelled. This will achieve the same thing you're trying to do with your updateFunction method, but it's cleaner as you only need to include the "do stuff" logic in the deferred function, and it's probably more performant as you won't be creating nested closures. Plus it's The Right way to do it which has got to count for something, right? :-)
(function(){
$('#my_div').css('background-color', 'red');
$('#my_div').hover(function(){
var id=setTimeout(function() {
$('#my_div').css('background-color', 'green');
}, 2000);
var id=setTimeout(function() {
$('#my_div').css('background-color', 'blue');
}, 4000);
var id=setTimeout(function() {
$('#my_div').css('background-color', 'pink');
}, 6000);
})
$("#my_div").click(function(){
clearTimeout(id);
})
})();
Related
I have got a problem with my clearInterval method.
I learn about JS in depth at FrontendMasters and there is an exercise where you need to use setInterval and log a string at every second and then run clearInterval after 5 seconds. I have access to the right solution but I would like to know why my solution is not working to get better understanding. The console.log('clear called', func); runs after 5 seconds and log the clear called string and the function body. I have tried to use setTimeout to wrap wrapper.stop() but it did not work that way either. I have used closures to try to solve the exercise. Here is my script.
function sayHowdy() {
console.log('Howdy');
}
function everyXsecsForYsecs(func, interval, totalTime) {
function clear() {
console.log('clear called', func);
clearInterval(func);
}
return {
start() {
setInterval(func, interval);
},
stop() {
setTimeout(clear, totalTime);
}
}
}
const wrapper = everyXsecsForYsecs(sayHowdy, 1000, 5000);
wrapper.start();
wrapper.stop();
Thanks
clearInterval does not take a function but a timer id which gets returned when using setInterval (so that you can set multiple timers onto the same function, and cancel them individually). To use that, declare a local variable inside everyXsecsForYsecs
var timer;
Then assign the timer to it:
timer = setInterval(func, interval);
Then you can clearInterval(timer).
I dont know why my code dont work. Please help!
$('nav').mouseout(setTimeout(function() {
$(this).removeClass('subm')
}, 1000));
Without setTimeout is work normaly.
setTimeout(...) is being called immediately. It returns the id number of the newly pending timeout. The timeout is only registered and called once here. The execution of your code is happening like this:
setTimeout(function() {
$(this).removeClass('subm')
}, 1000);
// = 2
$('nav').mouseout(2);
You need to pass .mouseout() a function that calls setTimeout each time. You also need to fix the this reference, which is different inside the setTimeout callback. This should fix both issues:
$('nav').mouseout(function() {
var self = this;
setTimeout(function() {
$(self).removeClass('subm')
}, 1000);
});
In javascript, like in most other languages, when you do this:
variable = some_function();
you're passing the return value of a function to a variable. Similarly when you do this:
a_function(another_function());
you're passing the return value of another function as an argument to a function.
This works the same in javascript, C, PHP, Ruby and even Fortran.
So, when you do this:
$('nav').mouseout(setTimeout(..));
You're passing the return value of setTimeout as an argument to mouseout. And setTimeout returns a number which can be used in clearTimeout. So you're basically doing this:
$('nav').mouseout(a_number);
What you want instead is to pass a function:
$('nav').mouseout(function(){setTimeout(..)});
Or if you find that hard to read then do this:
function handleMouseOut () {
setTimeout(...);
}
$('nav').mouseout(handleMouseOut); // note we're passing a function here
// not calling it
Which way is correct and more efficient in using setInterval() and clearInterval()?
1.
something = setInterval(function() {
try {
...load something
clearInterval(something);
} catch (e) {
// error
}
}, 5000);
2.
something = setInterval(function() {
try {
...load something
} catch (e) {
// error
}
}, 5000);
setTimeout(something, 7000);
EDIT:
For #2, I meant setTimeout() instead of clearInterval().Has been changed.
I assume the interval you're passing into clearInterval is meant to be something.
Your second example will never fire your timer, because you clear the timer immediately after setting it. You're also passing an argument (7000) into clearInterval that won't get used (clearInterval only accepts one argument).
Your first example is right provided that you want to clear the repeated timer at the point where you're calling clearInterval from within the handler. Presumably that's in an if or similar, because if you want a one-off timed callback you'd use setTimeout, not setInterval.
EDIT:
For #2, I meant setTimeout() instead of clearInterval().Has been changed.
That completely changes the question. No, that's not correct. setInterval schedules the function to be called repeatedly on the interval you give it, you don't pass its return value into setTimeout.
If you need something to happen over and over again you use setInterval if you only need it to happen once use setTimeout (you can simulate setInterval by chaining multiple timeouts one after the other). Timeouts only happen once therefore you do no need to clear them. Also clearInterval does not take a time argument so the interval you set will be cleared before it ever executes since classic javascript is synchronous.
just to complete the answer, take many care with setInterval(). if your "...load something" take sometime more time to load than the time according (for a reason or another). it will just don't do it for this time and will wait the next call of setinterval.
I encourage to use setTimeout() as much as possible instead.
You can find find below the use cases that are, according to me, aswering to your questions:
For your case 1:
var something = setInterval(function() {
// Do stuff, and determine whether to stop or not
if (stopCondition) {
clearInterval(something);
}
}, 5000);
For your case 2:
var something = setInterval(function() {
// Do stuff
}, 5000);
// Pass a function to setTimeout
setTimeout(function() {
clearInterval(something);
}, 17000);
If i'm calling 2 or 3 times a function, like this:
somefunction();
somefunction();
How could i know when is the last time the function has been called?
i'm asking that because i want the last function to do one more thing.
Pass a parameter that determines whether the function should do "one more thing"
somefunction(false);
somefunction(true);
You could set a timeout when the function is called, then the code will be called as soon as you exit from your first function returning control to the browser:
var timer = null;
function somefunction() {
// do something
if (timer == null) {
timer = window.setTimeout(function(){
// do one last thing
}, 0);
}
}
Demo: http://jsfiddle.net/Guffa/Fa5j3/
You can't know this.
If you know how often it is called, you can count down a variable.
If you don't know how often it is called you can start a timeout and call the special function. If you call someFunction again you cancel the old timeout and start a new timeout.
I use setInterval to run a function (doing AJAX stuff) every few seconds. However I also have an other function also calling it.
setInterval(myFunc(), 5000);
function buttonClick() {
// do some stuff
myFunc();
}
Most of the time it works, however sometimes this function gets called twice at the same time resulting in receiving exactly the same result twice, something I don't want.
I think I have to use clearTimeout:
var interval = setInterval(myFunc(), 5000);
function buttonClick() {
clearTImeout(interval);
// do some stuff
myFunc();
interval = setInterval(myFunc(), 5000);
}
However this causes the function to halt. Since it gets called from an other function some code never gets executed. How can I prevent this?
however sometimes this function gets called twice at the same time resulting in receiving exactly the same result twice, something I don't want.
JavaScript on browsers is single-threaded (barring using the new web workers stuff, but that wouldn't apply here anyway). Your function will never get called while it's running. (But more below.)
In your various code quotes, you're calling myFunc where you mean to just be referring to it. E.g.:
var interval = setInterval(myFunc(), 5000);
should be
var interval = setInterval(myFunc, 5000);
// ^--- No parentheses
Your code cancelling the timeout will work if you correct that:
var interval = setInterval(myFunc, 5000);
function buttonClick() {
clearTImeout(interval);
// do some stuff
myFunc();
interval = setInterval(myFunc, 5000);
}
But there's no reason to do that, myFunc cannot get called while it's running anyway.
If myFunc is triggering something that will complete asynchronously (an ajax call, for instance), the above won't help (for the simple reason that myFunc will start the process and then return; the process will complete separately). In that situation, your best bet is to have myFunc schedule its next call itself:
function myFunc() {
// Do my work...
// Schedule my next run
setTimeout(myFunc, 5000);
}
...and not use setInterval at all.
I realize there's a couple of solutions already, but thought I'd show one that has a tad more than just "do this". I tend to learn by example, and thought I would extend the same practice. That being said, the demo is here but I'll try to explain as well.
// Here we assign the function to a variable that we can use as an argument to the
// setInterval method.
var work = function(){
// performing a very simple action for the sake of demo
$('#log').append('Executed.<br />');
};
// this is a variable that is essentially used to track if the interval is or is
// not already running. Before we start it, we check it. Before we end it, we also
// check it. Let's start off with it started though
var worker = setInterval(work, 5000);
// bind to the start button
$('#start').click(function(){
// Test: is the worker already running?
if (worker)
// Yes it is, don't try to call it again
$('#warn').text('Timer already running!');
else{
// no it's not, let's start it up using that function variable we declared
// earlier
worker = setInterval(work,3000);
$('#warn').text('Started!');
}
});
// bind to the stop button
$('#stop').click(function(){
// test: is the worker running?
if (!worker)
// no, so we can't stop it
$('#warn').text('Timer not running!');
else{
// yes it's working. Let's stop it and clear the variable.
clearInterval(worker);
worker = null;
$('#warn').text('Stopped.');
}
});
Unless myFunc returns a function I would do this (also use clearInterval in stead of clearTimeout):
var interval = setInterval(myFunc, 5000);
function buttonClick() {
clearInterval(interval);
// do some stuff
myFunc();
interval = setInterval(myFunc, 5000);
}
setInterval expects a function in its argument. You call a function by using myFunc(). so whatever is returned by myFunc was passed to setInterval which is probably not what you want.