clearInterval() not working on button click - javascript

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.

Related

how to stop setInterval in react native

i am running a setinterval function to check for a payment from coinbase in my react native app, i run the function after every 10 seconds, after the payment has been made, i clear the setinterval and navigate to the homepage, but still the setinteval keeps running how can i stop this?
useEffect(() => {
getData();
myinterval();
}, []);
const myinterval= () => setInterval(function () {
checkCharge();
}, 10000);
const stopCounter = () => {
clearInterval(myinterval);
}
const checkCharge = async () => {
try {
...SOME_CODE_HERE...
stopCounter()
navigation.navigate("HomeScreen");
} catch (e) {
console.log(e);
}
};
i ran into a similar problem some months back, this soluion should work perfectly:
const myinterval = setInterval(function () {
checkCharge();
}, 10000);
but in my case, since I store the setInterval in a variable instead of a function, I had some weird problems, like the setInterval might run three times or keep on running even after I used clearInterval(INTERVAL_NAME); so if you want to check if a payment has been made, create a button that would tell the user to click when they have made the payment, this would be a lot safer than to run the function inside of setInterval
I believe it's because myinterval is assigned to a function and not the actual return value of the setInterval() function. So try to change
const myinterval = () => setInterval(function () {
checkCharge();
}, 10000);
to
const myinterval = setInterval(function () {
checkCharge();
}, 10000);
and then canceling the myinterval variable with clearInterval(myinterval);
You aren't using the return from myinterval() to clear the setInterval. setInterval() returns an id that is used to clear the interval. When you call the function myinterval, it is returning that ID. What you need to do is store that ID in a variable that you can use to clear the interval.
...
function createInterval(){
return setInterval(checkCharge, 10000);
}
function stopCounter(id){
clearInterval(id);
}
...
var id = createInterval();
...
function checkCharge(){
try {
...
stopCounter(id);
...
} catch(e){
console.error(e);
}
}

Clearing setinterval not working?

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);

Using clearInterval within a function to clear a setInterval on another function

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;
}

Can anyone explain why this JavaScript wont run

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.

setTimeout functionality is not working

I am trying to use the jQuery setTimeout in order to call a method each x time interval:
$('.text').blur(function () {
doSmth();
});
$('.text').bind("paste", function (e) {
setTimeout(function () {
doSmth();
}, 5);
});
The timeout is not working , please advice !
What do you mean with "it's not working"?Anyway setTimeout() is a Javascript function that triggers only once after the specified interval.
If you wan't to trigger something every five second you should do:
var interval = setInterval(doSmth, 5000);
Where doSmth is a function defined elsewhere and 5000 is the number of millisecond of the interval. If yo want to stop the execution just do:
clearInterval(interval);
First, it isn't a "jQuery setTimeout". setTimeout is part of the native API, not jQuery's API.
Second, I assume you want 5 seconds. Currently you're doing 5 milliseconds.
$('.text').bind("paste", function(e) {
setTimeout(function() {
doSmth();
}, 5000);
});
The duration of 5 in your code is far too short to be perceptible.
I see that the other answers user setInterval, but from what I've read, you should avoid using setInterval, since you can end up with a stack of not-yet-executed function calls etc.
So what you could do instead is something like this:
var myTimeout;
$('.text').bind("paste", function (e) {
function loopFunction () {
doSmth();
myTimeout = setTimeout(loopFunction, 5000);
}
myTimeout = setTimeout(loopFunction, 5000);
});
Now you have a function that calls itself every five seconds.
According to your feedback,here is the solution:
var interval = setInterval(doSmth, 5000);
$('.text').blur(function() {
doSmth();
});
$('.text').bind("paste", function(e) {
setTimeout(function() {
doSmth();
}, 0);
});
Thanks for you amazing support.

Categories

Resources