var theintrvl = function() {
setInterval(function () {
somefunction()
}, 3000)
}
the somefunction isn't important - all works just fine, BUT! When I try to clear the interval it doesn't clear. Here's what I tried:
document.getElementById('clearme').addEventListener('click', function() {
clearInterval(theintrvl);
});
I also tried somefunction instead the theintrvl, but nothing!
You don't need to wrap it in a function at first place. Just save the value returned by setInterval function
var theintrvl =
setInterval(function () {
somefunction()
}, 3000);
You need to have
var myinterval = setInterval(function, time)
And then to clear it you would do
clearInterval(myinterval)
You may want to get rid of the outside function though because myinterval wouldn't be accessable from outside theintervl
One more thing, you might consider doing
setInterval(somefunction, 3000)
Instead of calling the function from an anonymous function
Hope this helps!
Try this:
var test = setInterval(somefunction, 3000);
clearInterval(test);
Related
How can I stop this process after, say, 5 seconds?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function changeBanner(){
// my change banner code
}
window.onload = function () { setInterval(changeBanner, 100) };
</script>
So currently I am changing the banner every 100 milliseconds. But I'd like it to stop after about 5 seconds.
I thought setTimeout might do the trick;
window.onload = function () { setTimeout(setInterval(changeBanner, 100), 5000) };
But that makes no difference.
I'd like it to stop after about 5 seconds.
store the return value given by setInterval and use it with clearInterval
var timer = setInterval(changeBanner, 100);
setTimeout(function() {
clearInterval(timer)
}, 5000);
There are also several libraries that implement function wrappers to achieve the same. For example, in underscore.js you could use _.before:
var changeBannerLimited = _.before(50, changeBanner);
var timer = setInterval(changeBannerLimited, 100);
Note that contrary to using clearInterval this will continue to call the changeBannerLimited function forever, however after being called 50 times (10 * 5 seconds) it will no longer pass the call on to changeBanner.
On a side note I chose underscore.js because I know it well and because it provides nicely formated annotated source code so you can easily understand what's really going on behind the scenes.
You could store the return value of setInterval to a variable so that you can later cancel it:
function changeBanner(){
// my change banner code
}
window.onload = function () {
var id=setInterval(changeBanner, 100);
window.setTimeout(function() {
window.clearInterval(id);
},5000);
};
Use clearInterval.
window.onload = function () {
var bannerInterval = setInterval(changeBanner, 100);
setTimeout(function() {
clearInterval(bannerInterval);
}, 5000);
};
persist setInterval output in variable to be able to call clearInterval;
window.onload = function () {
var job= setInterval(changeBanner, 100) ;
setTimeout(clearInterval(job), 5000)
};
I think im missing something fairly obvious with how the clearInterval method works.
So with the code below. I would expect the first function call to execute testFunction and set the interval to repeat the function. The 2nd call would execute the second function which will remove the interval from the 1st function. As this would execute far before the 5000ms interval the first function would not be executed again. However it does not behave like this.
Could someone please explain what is wrong with my method?
Reason for this is in a program I am writing I am making repeated get requests, every 30 seconds or so , using setTimeout but i would like a method to easily remove this interval at other points in the program
function testFunction() {
$("#test").append("test");
setTimeout(testFunction, 5000);
}
function stopFunction() {
clearTimeout(testFunction);
}
testFunction();
stopFunction();
setTimeout returns an ID so you should
var timeoutID = setTimeout(blah blah);
clearTimeout(timeoutID);
setTimeout returns an object that you need to pass into the clearTimeout method. See this article for an example: http://www.w3schools.com/jsref/met_win_cleartimeout.asp
setTimeout returns an identifier for the timer. Store this in a variable like:
var timeout;
function testFunction(){
...
timeout = setTimeout(testFunction, 5000);
}
function stopFunction(){
clearTimeout(timeout);
}
Here is a simple and I think better implementation for this .
var _timer = null,
_interval = 5000,
inProgress = false,
failures = 0,
MAX_FAILURES = 3;
function _update() {
// do request here, call _onResolve if no errors , and _onReject if errors
}
function _start() {
inProgress = true;
_update();
_timer = setInterval(_update, _interval);
}
function _end() {
inProgress = false;
clearInterval(_timer);
}
function _onReject(err) {
if (failures >= MAX_FAILURES) {
_end();
return false;
}
_end();
failures++;
_start();
}
function _onResolve(response) {
return true;
}
I have a HTML page with two buttons and I want to use setInterval to evaluate the function multiple times when I click the start button. This works just fine but I can't clear the interval. What am I doing wrong?
function intFunc (func, time) {
interval = setInterval(func, time);
}
$("#startButton").on("click", intFunc(function () {
$.post('link/to/php.php', function(data) {
//do something with data
});
}, 1000));
$("#stopButton").on("click", function () {
clearInterval(interval);
});
First, as the comments suggest you should declare interval above to make sure the scope is clear.
Second, you have a syntax problem. You're invoking intFunc straight away, and passing the result to $("#startButton").on(). This isn't what you want. What you should be passing as that second argument is a callback function. You could reorganize your code like this perhaps:
Third, declaring within a self invoking anonymous function will prevent pollution of the global scope.
(function() {
var interval;
$("#startButton").on("click", function(){
interval = setInterval(function () {
$.post('link/to/php.php', function(data) {
//do something with data
});
}, 1000);
});
$("#stopButton").on("click", function () {
clearInterval(interval);
});
})();
This is how you should (or could) have written it:
var interval;
$("#startButton").on("click", function(){
interval = setInterval(function () {
$.post('link/to/php.php', function(data) {
//do something with data
});
}, 1000);
});
$("#stopButton").on("click", function () {
clearInterval(interval);
});
You cannot use functions like that, because when you write:
$("#startButton").on("click", intFunc(..));
You are executing intFunc immediately, and that doesnt return anything.
Im not very good wit JS and I just dont get why this wont work!
The code uses jquery to apply the pulsate efect to one of my divs and run forever unless I stop it with another function, but I cannot figure our why my first piece of code wont run!
function animate(var x){
// Do pulsate animation
$(x).effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(animate, 10000);
}
$(document).ready(animate("#mydiv"));
Only way to get it working is for me to do this
function animate(){
// Do pulsate animation
$("#mydiv").effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(animate, 10000);
}
$(document).ready(animate);
Note that in the first snippet the code uses variables to be more useful and the second piece has the selectors name hardcoded
Don't use var in your function declaration. Just use:
function animate(x){
Also, you probably want something like this for your first example:
function animate(x){
return function () {
function animateInner() {
$(x).effect("pulsate", { times:4 }, 5000);
setTimeout(animateInner, 10000);
}
animateInner();
};
}
$(document).ready(animate("#mydiv"));
DEMO: http://jsfiddle.net/XHKbC/
Otherwise, the original animate("#mydiv") call executes immediately (and $(x) probably won't find anything since the DOM isn't ready yet). $(document).ready() expects a reference to a function. You called a function instead. But that's all a little overkill. Just use:
$(document).ready(function () {
animate("#mydiv");
});
but you'll have to change your function so the setTimeout passes the value of x as well:
function animate(x){
// Do pulsate animation
$(x).effect("pulsate", { times:4 }, 5000);
// set timeout and recall after 10secs
setTimeout(function () {
animate(x);
}, 10000);
}
DEMO: http://jsfiddle.net/XHKbC/2/
Although it's a little more code/complex, my first example doesn't suffer the problem in my second (having to pass x in the setTimeout) by using a closure.
UPDATE:
Being shown how you are using this code, I'd set it up like this:
function Animater(target) {
var self = this;
var animateTO;
var animateElement = target;
function animate() {
animateElement.effect("pulsate", { times:4 }, 5000);
animateTO = setTimeout(animate, 10000);
}
self.start = function () {
animate();
};
self.stop = function () {
animateElement.finish();
clearTimeout(animateTO);
};
}
And create a new one like:
var mydivAnimater = new Animater($("#mydiv"));
You can then call .start() and .stop() on it, and you create any number of these Animater objects on different elements as you want.
DEMO: http://jsfiddle.net/K7bQC/3/
Your code has two issues:
omit the var:
function animate(x){
modify your event handler:
$(document).ready(function(){
animate("#mydiv");
});
You need to hand over a function reference (either animate or function(){}), not run the code right away which you are doing if you pass animate().
Now to not lose the reference to your x you have to modify the animate call in the timeout too:
setTimeout(function () {
animate(x);
}, 10000);
You dont need to type var when specifying a function parameter.
I am just trying to implement the most basic example of setInterval with jQuery and am having problems. What's wrong here?
It says function rotate is not defined.
$(document).ready(function() {
var speed = 5000;
var run = setInterval("rotate()", speed);
function rotate() {
alert ('rotate');
}
});
Do this instead:
$(document).ready(function() {
var speed = 5000;
function rotate() {
alert ('rotate');
}
var run = setInterval(rotate, speed);
});
You could also simply do this:
$(function() {
var speed = 5000;
var run = setInterval(function() {
alert ('rotate');
}, speed);
});
You should declare run outside the ready event handler if you wish to be able to clear the interval later though, since it will go out of scope otherwise.
You are passing setInterval a string to eval. This is:
Hard to debug
Inefficient
Ugly
executed in a different scope
The function is limited in scope to the function it is defined inside.
Pass the function directly instead
var run = setInterval(rotate, speed);
omit the parenthesis and quotes around rotate in your setInterval call. You are giving it the function itself, not the name. It shouldn't matter the order that they go in.
That's effectively eval-ing rotate in (what I believe is) its own context. Change it to
var run = setInterval(rotate, speed);
and it should be fine.
or even put the rotate function outside the ready function.
this works
$(document).ready(function() {
function rotate() {
alert ('rotate');
}
var speed = 5000;
var run = setInterval(function() { rotate() }, speed);
});
$(function() {
var speed = 5000;
var rotate = function() {
alert("rotate");
};
window.setInterval(rotate, speed);
});
You need to define rotate in the global scope.
$(document).ready(function() {
window.rotate = function() {
alert ('rotate');
}
var speed = 5000;
var run = setInterval("rotate()", speed);
});