Change interval of setInterval [duplicate] - javascript

This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 10 years ago.
Is there a way of modifying the interval of calls of function set with setInterval during runtime, other than removing it (clearInterval) and reinstating again with a different value?

Use setTimeout instead, additionally this a non-blocking method for async JS:
var interval = 1000;
function callback() {
console.log( 'callback!' );
interval -= 100; // actually this will kill your browser when goes to 0, but shows the idea
setTimeout( callback, interval );
}
setTimeout( callback, interval );
Don't use setInterval, as in some cases (lots of setInterval + long callbacks, which are usually longer than timeout), due to limited queue size, some callbacks will be dropped by the browser and never executed. Only setTimeout guarantees execution.

Nope; removing the interval and re-adding it is the way to do it if you've used setInterval().
You could accomplish the same goal of a varying timeout, however, by calling setTimeout() repeatedly with a variable delay at the end.
Out of curiosity, what are you doing that you want to modify the interval? Perhaps requestAnimationFrame() might be more appropriate?

Related

Node.js setTimeout in forever loop [duplicate]

This question already has answers here:
Callback of an asynchronous function is never called
(1 answer)
setTimeout not working inside infinite loop
(5 answers)
Closed 5 years ago.
Can't explain nodejs behavior. I have code:
while (true) {
setTimeout(() => console.log(1), 0)
}
And this script just hanging...
How come? I've been thinking setTimeout is non-blocking and asynchronous, and nodejs use timers event loop phase for scheduling setTimeout callbacks... but it seems like event loop blocked...
Your while loop is infinite. It will just keep setting timeouts and never exiting the loop. Since JavaScript is single-threaded, the code for the timeouts won't run until the current code is finished, and since the while loop never finishes, the timeouts don't run.
If you want to spam the console with the number 1 using timeouts, which it looks like you are trying to do, you would have to set the next timeout in the current timeout's callback:
function timeoutFunc() {
console.log(1);
setTimeout(timeoutFunc, 0);
}
timeoutFunc();

Maximum call stack size exceeded on SetTimeout recursive function (Javascript) [duplicate]

This question already has answers here:
setTimeout calls function immediately instead of after delay
(2 answers)
Closed 6 years ago.
I have a recursive SetTimeout function that clicks a filter on my page after the filters have loaded (they're loaded through Ajax, so not available immediately on page load).
$scope.clickFilter = function () {
var filter = $('.filter-item')
.find('input[value="' + $scope.activeFilter + '"]');
if (filter.length < 1) {
setTimeout($scope.clickFilter(), 1000);
} else {
$(filter).trigger("click");
}
}
However, when the filters take a long time to load, I get "Uncaught RangeError: Maximum call stack size exceeded(…)"
How do I prevent this and make sure it runs until completion?
The problem is here:
setTimeout($scope.clickFilter(), 1000);
Putting () after the function reference means that you want the function to be called, immediately, at that point in the code. What you probably want instead is something like:
setTimeout($scope.clickFilter.bind($scope), 1000);
which will
pass a function reference to setTimeout(), as is required, and
ensure that the function will be invoked with the proper this value (what the .bind() part does)
Once you get it working, the term "recursive" isn't really appropriate. Yes, the function is referencing itself when it arranges for the call after the timer expires, but it's not directly calling itself; it's asking something else (the timer mechanism) to call it later.

is setInterval more likely to occur on time than continuous setTimeout calls [duplicate]

This question already has answers here:
setTimeout or setInterval?
(20 answers)
Closed 8 years ago.
I have these snippets of code that do the same thing but use different approaches - setInterval and continuous setTimeout calls:
function log() {
console.log('fn')
}
//option 1
var forTimes = 10;
var doneTimes = 0;
var interval = setInterval(function(){
if (doneTimes < forTimes) {
log();
doneTimes++;
} else {
clearInterval(interval);
}
}, 100);
//option 2
function timeoutFn() {
if (doneTimes < forTimes) {
log();
doneTimes++;
setTimeout(timeoutFn, 100);
}
}
setTimeout(timeoutFn, 100);
Because of the nature of single-threaded javascript neither setTimeout nor setInterval guarantees functional call witing 100 ms since thread may be busy running an event handler or doing reflow/repaint. I'm wondering if any of them has higher likelyhood of executing handler within the specified time? If so, why? Does setInterval act like setTimeout in that it waits for the specified interval to pass and only after that adds handler to the queue?
setInterval is kind of seen as bad practice these days because you have a function being executed at intervals regardless of whether or not the previous call to the function has completed.
With regards to exact time neither is better or worse really.
The best method would be to do a recursive setTimeout Pattern:
var count = 0;
(function loopsiloop(){
setTimeout(function(){
if(count < 10) {
loopsiloop();
}
++count;
}, 100);
})();

setTimeout not working in NodeJS [duplicate]

This question already has answers here:
Why is setTimeout executing immediately? [duplicate]
(4 answers)
Closed 8 years ago.
I have this slideUp function that calls the animate function. The objective is to make a div appear to
slide up on the screen by recalling the animate function every 20ms, and rerendering the div in the browser after adjusting the css for the div position.
I'm using Node js, and due to the
asynchronous behaviour, I believe that the timeout only gets involked once, and that the program continues running while it waits on the timeout to complete.
When i print the value of 'bottom' to the console, it has looped through 20 times as expected. Only the final view
gets rendered thou. Can anyone offer any way to get around this problem so that it rerenders each of the 20 times?
slideUp: function () {
var bottom=0;
this.animate(bottom);
},
animate: function(bottom){
bottom++;
if (bottom<20){
this.view.getClientNotificationElement().setAttribute("style","margin-bottom:"+bottom+"px");
this.clientNotification.attachTo(this.view.getClientNotificationElement());
setTimeout(this.animate(bottom), 20);
console.log(bottom);
}
}
You are passing the return value of this.animate(bottom) to setTimeout.
The animate function doesn't have a return statement, so it returns undefined.
The effects of the function happen immediately (because you are calling it) and then setTimeout does nothing.
Pass a function to setTimeout instead.
var self = this;
var callback = function () {
self.animate(bottom);
};
setTimeout(callback, 20);

Call a Javascript function every 5 seconds continuously [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling a function every 60 seconds
I want to Call a Javascript function every 5 seconds continuously.
I have seen the setTimeOut event. Will it be working fine if I want it continuously?
You can use setInterval(), the arguments are the same.
const interval = setInterval(function() {
// method to be executed;
}, 5000);
clearInterval(interval); // thanks #Luca D'Amico
Do a "recursive" setTimeout of your function, and it will keep being executed every amount of time defined:
function yourFunction(){
// do whatever you like here
setTimeout(yourFunction, 5000);
}
yourFunction();
As best coding practices suggests, use setTimeout instead of setInterval.
function foo() {
// your function code here
setTimeout(foo, 5000);
}
foo();
Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout function that will be later call the same function again.
For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:
setInterval(function() {
// do stuff
}, duration);
Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/
Plus:
has nice fade in / fade out animation
will pause on :hover
will prevent running multiple actions (finish run animation before starting second)
will prevent going broken when in the tab ( browser stops scripts in the tabs)
Tested and working!

Categories

Resources