clearInterval() what happens with the last interval call - javascript

var interval = setInterval(function()
{ function }, 1000);
clearInterval(interval);
What happens with the last interval call when clearInterval is called? If the interval is 500 out of 1000 (.5 seconds) into the interval and clearInterval is called, does this function get called and then the interval is cancelled? Or does the function not get called and the interval is cancelled?
Thanks

If the specified interval hasn't yet elapsed, the callback will not be invoked again. The standard isn't clear on what would happen if the interval has elapsed but the callback has not yet been processed by the event queue, but in the case where there are 500 ms remaining before the next invocation, it definitely shouldn't invoke the callback again.

You can test it out with something like:
var counter = 0;
var interval = setInterval(function() {
console.log(counter);
counter++;
}, 2000);
setTimeout(function() {
clearInterval(interval);
}, 5900);
=> 0
=> 1
As you can see, if the interval is interrupted midway, the callback won't be executed.

Related

setTimeout in JS

function x() {
for (let i = 1; i <= 5; i++) {
setTimeout(function() {
console.log(i);
}, i * 1000);
}
console.log("Hello World!!");
}
x();
The above function produces the output 1 to 5 but it's taking 1 second to produce each output. And that's what I am not getting... Why is it taking 1 second each and why not 1 second for first value of i, then 2 seconds for second value of i and so on and so forth as I am multiplying the milliseconds with the i value?
The main confusion you are having is pretty common and comes from the fact that you are using a loop. Everything outside of the timer callback is JavaScript that is being executed synchronously with no delay. The loop executes 5 times immediately when you run the code and so 5 instances of the timer callback function get placed on the event queue in a matter of milliseconds and it is from that point in time that all 5 timer callbacks are delayed, rather than one callback being delayed from the completion of the prior one.
The first instance of the callback then runs after its initial delay is reached (1 second), then the second instance runs after its delay (2 seconds, which is only 1 second later than when the first function call ran) and then the third one runs (which is only 1 second behind the previous one of 2 seconds) and so on.
What you need to do is place the first instance of the callback on the event queue with a 1 second delay before it runs and then, when that first instance has completed, place another instance on the event queue with a 2 second delay, and so on.
To do this, forget the loop and make the timer function recursive, which will essentially cause a repeating code call, just as a loop would.
let delay = 1000;
let timer = null; // Will hold a reference to the timer
function x() {
timer = setTimeout(function(){
console.log(delay / 1000);
delay += 1000;
if(delay > 5000){
clearTimeout(timer); // Cancel the timer
console.log("Operation Complete!");
} else {
// Because the next call for the parent function comes from within
// the timer callback function, it is delayed until the end of that
// callback function's execution.
x();
}
}, delay);
}
x();
If you want the behaviour of adding a i seconds each time, do something like:
function x(i, max = Infinity) {
if (i > max) return
console.log("Hello World!! %s", i);
setTimeout(function() {
console.log(i);
x(i + 1, max)
}, i * 1000);
}
x(1, 5);

clearInterval not working from interval inside setTimeout

Clear interval is not working for an interval i use inside setTimeout().
var $scroller;
setTimeout(function() {
var div = jQuery('.module-content-slider');
$scroller = setInterval(function(){
/* interval function */
}, 25)
}, 1000);
clearInterval($scroller);
The clearInterval runs before setInterval within the "timeout" after 1 second (1000 milliseconds) is executed — effectively clearing an unset $scroller interval.
There is no what to clear.
The interval doesn't exist at clearInterval($scroller); run time.
clearInterval will be executed a second later.
Looks like your use case is to trigger interval function for every 25 ms and clear the interval after 1000 ms.
If thats the scenario then it should be
var $scroller = setInterval(function(){
/* interval function */
}, 25);
setTimeout(function() {
var div = jQuery('.module-content-slider');
clearInterval($scroller);
}, 1000);

How to make setInterval() to wait for an interval (like 10 seconds) before EVERY iteration?

The normal behavior of setInterval(function() {...}, intervalInMilliseconds) in Javascript is such that it is called for the first time after intervalInMilliseconds milliseconds, and after that continues to run again and again without any delay or wait.
I need my code to be executed after every, say, 10 seconds. The following will execute the function for the first time after 10 seconds and then continue to execute it again and again (until clearInterval() is called) without any delay/wait.
setInterval(function() {
//code, e.g. some AJAX request
}, 10000);
I need each iteration to be executed after a 10 seconds delay. How can I do that?
So, as I understand it, you want the "loop" to execute 10 seconds after your code has completed? If so, you could do something like this...
Execute your synchronous long running code
Execute another loop, 10 seconds later (I've used 1 second in the example)
Synchronous example...
var loop = () => {
setTimeout(() => {
doSyncWork()
loop()
}, 1000)
}
loop()
Or asynchronously (e.g. ajax)...
var loop = () => {
setTimeout(() => {
doAsyncWithCallback(loop)
}, 1000)
}
loop()
Or with a Promise...
var loop = () => {
setTimeout(() => {
doAsyncWithPromise().then(loop)
}, 1000)
}
loop()
The normal behavior of setInterval(function() {...},
intervalInMilliseconds) in Javascript is such that it is called for
the first time after intervalInMilliseconds milliseconds, and after
that continues to run again and again without any delay or wait.
thats not true.
mormal behavior of setInterval is to execute callback every n milliseconds.
every callback call will occur after previous callback invocation over n milliseconds.
take a look
let counts = 0;
let interval = setInterval(() => {
console.log(counts % 2 == 0 ? 'tick' : 'tack');
counts++;
if (counts == 5)
clearInterval(interval);
},1000);
I need each iteration to be executed after a 10 seconds delay. How can
I do that?
like this:
setInterval(callback, 10000);
every callback will be called each ten seconds

Stopping setInterval() after 2 second

I have tried set interval, so that the function computercardArrange() should be called called only one time after 2 second. But it is calling the function computercardArrange() countiniously after 2 sec. How can i stop so that the function computercardArrange() is called only one time after 2 sec. Below is the code.
function timer() {
setInterval(function(){
computercardArrange(); // This function should be called only one time after 2 second.
}, 2000);
}
Just use setTimeout instead
function timer() {
setTimeout(function(){
computercardArrange(); // This function should be called only one time after 2 second.
}, 2000);
}
What if i want to call that function 10 times and the stop the
interval?
var callCount = 0 ;
function timer() {
var intervalIdentifier = setInterval(function(){
computercardArrange();
if (++ callCount == 10) {
clearInterval(intervalIdentifier);
}
}, 2000);
}

interval keeps firing even though clearInterval has been called

I am trying to get a function to run 10 times with a pause inbetween each run, yet when I try to it repeats the function infinite times then after 10 times it pauses, and so on. Right now this is the code with the problem:
for(i=0;i<10;i++) {
console.log(i);
interval = setInterval(function() {console.log("Function ran");}, 1000);
}
window.clearInterval(interval);
Console:0123456789Function ran["Function ran" is repeated infinite times after "9"]
interval = setInterval(function() {console.log("Function ran");}, 1000);
This line creates a new interval-instance each time, which means you have created 10 intervals. At the end of the loop interval holds the id of the last interval that was created. Hence that's the only one you're clearing, and the other ones are still running.
To cancel the interval, you need to keep track of how many times the function has been invoked. One way you can do that is as follows:
function pauseAndRepeat(delay, iterations, func) {
var i = 0;
var interval = setInterval(function() {
func();
if(++i === iterations) {
clearInterval(interval);
}
}, delay);
}
Here we have a function that defines a counter (i) in its local scope. Then it creates an interval using a function that checks the counter to see if it should call your function (func) or clear the interval when it is done. interval will have been set when the interval-handler is actually called. In this case the handler is basically a closure since it is bound to the local scope of pauseAndRepeat.
Then you can invoke the function as follows:
pauseAndRepeat(1000, 10, function() {
console.log("Function ran");
});
This will print out Function ran ten times, pausing for a second each time.
setInterval is expected to run forever, on an interval. Every time you call setInterval here, you have a new infinite loop running your function every 10s, and as others have noted you only are canceling the last one.
You may do better with chained setTimeout calls:
var counter = 0;
function next() {
if (counter < 10) {
counter++;
setTimeout(function() {
console.log("Function ran");
next();
}, 1000);
}
}
next();
This chains delayed functions, setting a timeout for the next one after each runs. You can do something similar with setInterval and cancellation:
var counter = 0;
var intervalId = setInterval(function() {
console.log("Function ran");
if (++counter >= 10) {
clearInterval(intervalId);
}
}, 1000);
In both these cases the key issue is that you trigger the next run or cancel the interval within the callback function, not in synchronous code.

Categories

Resources