How to create a function setInterval with clearInterval inside it? - javascript

I have a app that must send the user to homepage after some events. For this I use this bit of code that works good:
var waitime = 1000;
var handle=setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
But I was trying to create a function to be called instead copy the code every time. So, after some reseach setInterval and how to use clearInterval and clearInterval outside of method containing setInterval I have create this one:
function refreshToHomePage3(handle,waitime){
return setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
}
The problem is when a call the function, like this:
var refreshIntervalId=refreshToHomePage3(refreshIntervalId,waitime);
I have a infinite loop. I already solved the problem using setTimeout instead of setInterval and the function became like this one:
function refreshToHomePage2(waitime){
setTimeout(function () {
$('.wrapper').html(divResposta);
$('body').append(js);
}, waitime);
}
But I was wondering how to solve the problem using setInterval and clearInterval. Any thougths?

setTimeout is prefered here. But you can use setInterval like this..
function refreshToHomePage3(handle,waitime){
handle = setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
return handle;
}
Actually there is no need to pass a handle variable into the function.
function refreshToHomePage3(waitime){
var handle = setInterval(function () {
alert("called after waitime");
clearInterval(handle);
}, waitime);
return handle;
}
var handle = refreshToHomePage3(5000);

You're clearing the interval after the first time the code runs. So what you're doing is just what setTimeout does. You need setTimeout which runs only once after the waiting for waitTime.
function refreshToHomePage(handle, waitime) {
setTimeout(function() {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
}

If you want your code to be executed just once after the wait time, setInterval is not the right function for this job, but setTimeout is.
setInterval will execute your code every n seconds until you execute clearInterval. However, setTimeout will execute your code once after n seconds and is therefore the correct approach for your problem.
Don't try to make setInterval something that it isn't :)

Related

setTimeout only executes once

Why is the setTimeout only being called once?
repeatSubscriber = function(observer) {
observer.next('first');
(function() {
setTimeout(() => {
observer.next('repeating timed resp');
}, 3000);
}());
};
Prints:
first
repeating timed resp
setTimeout() is only supposed to trigger once - what you need is setInterval().
Because it should:
setTimeout() sets a timer which executes a function or specified piece of code once after the timer expires.
More at MDN
What you are looking for is setInterval()
repeatSubscriber = function(observer) {
observer.next('first');
(function() {
setInterval(() => {
observer.next('repeating timed resp');
}, 3000);
}());
};
Because it worked like this its in the function nature,
If you need repeated call you need setInterval function

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.

setTimeout and setInterval not working

I want to be able to call the function work() every 6 seconds. My jQuery code is
function looper(){
// do something
if (loopcheck) {
setInterval(work,6000);
}
else {
console.log('looper stopped');
}
}
The problem I am running into is that it loops over work twice quickly, and then it will wait for 6 seconds. i tried using setTimeout with similar results.
What could be causing work to be called twice before the delay works?
setInterval should be avoided. If you want work to be repeatedly called every 6 seconds, consider a recursive call to setTimeout instead
function loopWork(){
setTimeout(function () {
work();
loopWork();
}, 6000);
}
Then
function looper(){
// do something
if (loopcheck) {
loopWork()
}
else {
console.log('looper stopped');
}
}
And of course if you ever want to stop this, you'd save the value of the last call to setTimeout, and pass that to clearTimeout
var timeoutId;
timeoutId = setTimeout(function () {
work();
loopWork();
}, 6000);
Then to stop it
clearTimeout(timeoutId);
Use old-style setTimeout()
var i=0;
function work(){
console.log(i++);
}
function runner(){
work();
setTimeout(runner, 6000);
}
runner();
I prefer the following pattern myself I find it easier to follow:
function LoopingFunction() {
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
And if you want to be able to stop it at any point:
var LoopingFunctionKeepGoing = true;
function LoopingFunction() {
if(!LoopingFunctionKeepGoing) return;
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
Now you can stop it at any time by setting LoopingFunctionKeepGoing to false.

Categories

Resources