Call a Javascript function every 5 seconds continuously [duplicate] - javascript

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!

Related

Javascript code doesn't work as expected [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.

Why does html onclick runs when it added by 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.

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

Change interval of setInterval [duplicate]

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?

Is there a sleep function in JavaScript? [duplicate]

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 9 years ago.
Is there a sleep function in JavaScript?
If you are looking to block the execution of code with call to sleep, then no, there is no method for that in JavaScript.
JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.
setTimeout(myFunction, 3000);
// if you have defined a function named myFunction
// it will run after 3 seconds (3000 milliseconds)
Remember, this is completely different from how sleep method, if it existed, would behave.
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
If you run the above function, you will have to wait for 3 seconds (sleep method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep function like that in JavaScript.
function test2()
{
// defer the execution of anonymous function for
// 3 seconds and go to next line of code.
setTimeout(function(){
alert('hello');
}, 3000);
alert('hi');
}
If you run test2, you will see 'hi' right away (setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.
A naive, CPU-intensive method to block execution for a number of milliseconds:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
You can use the setTimeout or setInterval functions.
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.

Categories

Resources