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;
}
Related
So from what I have understood, setInterval() is used to call a function on repeat on regular intervals.
So basically it is a loop that executes a function forever periodically.
I am confused as to if I had to stop this execution at one point what would be the way to do it
for eg I am trying to print the message "hey" 3 times after 1 second each, but somehow it is printing it 3 times every second and is going on forever.
What can I do to stop it after a set number of times.
This is the code that I've been trying
var i = 3;
function message() {
console.log("hey");
}
while(i > 0) {
setInterval(message, 1000);
i = i - 1;
}
Your code is executing the setInterval thrice in the while loop, which is not needed.
Actually, setInterval does not work as a function call but actually registers a function to be called at some interval.
The setInterval() method will continue calling the function until clearInterval() i.e it is deregistered or the process is killed.
It should work like this
var i = 3;
var interval = setInterval(message, 1000);
function message() {
if (i === 0) {
clearInterval(interval);
}
console.log("hey");
i = i - 1;
}
To clear a setInterval, use global clearInterval method.
Example:
var timerId = setInterval(func, 500);
.... some code here....
clearInterval(timerId);
What can I do to stop it after a set number of times.
usually you don't use setInterval() for this, you use setTimeout().
Something like
var counter = 0;
function message() {
console.log("hey");
// we trigger the function again after a second, if not already done 3 times
if (counter < 3) {
setTimeout(message, 1000);
}
counter++;
}
// initial startup after a second, could be faster too
setTimeout(message, 1000);
The setInterval function calls the function indefinitely, whereas setTimeout calls the function once only.
Simply use clearInterval once the count runs out.
var i = 3;
function message(){
console.log("hey");
if (--i < 0) {
clearInterval(tmr);
}
}
var tmr = setInterval(message, 1000);
you have to assign that setInterval to a javascript variable to name it what for this setInterval, like this
var messageLog = setInterval(message, 1000);
After, in setInterval message function add this condition to clear the inverval whenever you want to clear.
function message(){
if(i>3) {
clearInterval(messageLog); // clearInterval is a javascript function to clear Intervals.
return null;
}
console.log("hey");
}
You can retrieve the timer when creating and clear it if needed.
var i=3;
var timer = setInterval(message,1000);
function message(){
console.log("hey");
i—-;
if(i==0)
clearInterval(timer)
}
a beginner here too,look for clearInterval method ...
I have two functions for eg., runslider() and runslider1().
runslider() runs after the document is loaded and I need to call runslider1() after finishing runslider(). Then again runslider() after runslider1(). This process should happen like infinite loop. Can someone help me please.
I have tried to keep them like callbacks. But that didn't work.
function runSlider(runslider1){
alert("run")
runSlider1(runSlider());
}
function runSlider1(runslider){
alert("run1");
runSlider(runSlider1());
}
if you want your functions to be called over and over again try using setInterval
function runSlider(){
alert("run");
runSlider1();
}
function runSlider1(){
alert("run1");
}
setInterval(runSlider, 100);
This will cause both functions to be called in that order repeatedly every 100ms. It seems like this is the behavior you are looking for.
The comments above are correct - you will cause a stack overflow.
Don't know why you would need this, but I cleaned your code for you:
function runSlider() {
alert('run');
runSlider1();
}
function runSlider1() {
alert('run1');
runSlider();
}
You can create infinite loop like this you just need to call one function.
var runSlider = function() {
console.log("run")
runSlider1()
}
var runSlider1 = function() {
console.log("run1");
setTimeout(function() {
runSlider()
}, 1000)
}
runSlider()
Another solution is:
function runSlider() {
console.log("run");
runSlider1();
setTimeout(runSlider1(), 1000) // Calls runSlider1() after 1 second(1000 millisecond). You can change it.
}
function runSlider1() {
console.log("run1");
setTimeout(runSlider(), 1000) // Calls runSlider1() after 1 second(1000 millisecond).
}
runSlider(); // Starts the cycle
var maxCalls = 0;
function run1(cb) {
alert('run1');
if (maxCalls++ < 5) { //Added this to avoid an infinite loop
cb(run1); //We want the function run after cb to be this one
}
}
function run2(cb) {
alert('run2');
if (maxCalls++ < 5) {
cb(run2);
}
}
This is the way to call one function from another. If you create an infinite loop, you will freeze the browser up. If you want the two functions running constantly, its best to release execution for a bit with a setInterval call instead.
var runFunc = 0;
var run1 = function() {
alert('run1');
};
var run2 = function() {
alert('run2');
};
var run = function() {
!(++runFunc) ? run2 : run1; //Alternate between calling each function
}
var stopRunning = function() { //Call this to stop the functions running
clearInterval(runInterval);
};
var runInterval = setInterval(run, 1000); //Calls the function every second
So my hmtl eventhandeling button is
<input type="button" value="Stop" onclick="stop()">
and the javascript function stop() is:
function stop()
{
stop.called = true;
}
and I call this function here:
....
var interval = setInterval(function ()
{
// call generation again for each generation, passing in the previous generations best offspring
best_offspring = generation(best_offspring, characters, amount_offspring, mutation_rate, target_text);
document.getElementById("output_text").value = best_offspring;
document.getElementById("generations").value = generations;
if (score_met)
{
clearInterval(interval);
}
}, delay);
if (stop.called)
{
return;
}
// so that we know that the program has been run atleast once
start = true;
}
Do you need more of the code?
Anyway, what I want is to stop the execution when the function is called. But my interval loop continues even though the stop() function is called. I have also tried to put the ´if(stop.called)insidevar interval` loop. But that didnt work either.
Any ideas? Do I need to provide more info?
if (stop.called)
{
clearInterval(interval);
}
¿?
var interval = setInterval(function ()
{
// call generation again for each generation, passing in the previous generations best offspring
best_offspring = generation(best_offspring, characters, amount_offspring, mutation_rate, target_text);
document.getElementById("output_text").value = best_offspring;
document.getElementById("generations").value = generations;
if (score_met || stop.called)
{
clearInterval(interval);
}
}, delay);
if (stop.called)
{
clearInterval(interval);
return;
}
// so that we know that the program has been run atleast once
start = true;
}
SetInterval returns an Id so you can simply call clearInterval(id);. Return break etc. Doesnt work because it is not really a loop like for and while.
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 :)
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.