I have an app that gets data from a web service. I want to know that whether there is any way while the app is open but not being used to run a function every few minutes.
Basically, I want to check internet connectivity and check to make sure my web service is up.
You can use setInterval or use setTimeout.
setInterval works like a constant loop, so you can get a time for 3 seconds and every second it would run the code inside of the setInterval like so
setInterval(function()
{
alert("Hello");
}, 3000);
setTimeout works after a specific amount of time has gone by and then runs some code like so
setTimeout(function()
{
alert("Hello");
}, 3000);
The timer is in milliseconds so 1000 = 1 second
setInterval(function() {
alert("Will run every 5 seconds");
}, 5000);
setTimeout(function() {
alert("Will only run once after 5 seconds");
}, 5000);
Edit
As taxicala mentioned in the comments, the function will not be executed UNTIL 5 seconds has passed. If the thread is busy, it might be considerably longer than that. Most of the time it is a non-issue though, but worth having in mind.
Yes, you can use the setInterval function like:
var myVar = setInterval(function(){ yourKeepAliveFunction() }, 1000);
In the example above, yourKeepAliveFunction will run every second (1000 ms); myVar holds a handle to the timer, so once you want to stop running it, you can do so like:
clearInterval(myVar);
Related
I tried to make a stopwatch in the console, but the message kept on clearing before I had time to read it.
I tried increasing how long the Timeout function would go, but for some reason, it didn't make a difference.
Can somebody help me with making the messages not clear so fast?
setTimeout(function() {
console.log("1");
}, 1000);
setTimeout(function() {
console.clear()
},1099);
setTimeout(function() {
console.log("2");
}, 2000);
setTimeout(function() {
console.clear()
}, 2099);
setTimeout(function() {
console.log("3");
}, 3000);
setTimeout(function() {
console.clear()
}, 3099);
second argument to settimeout represents time in milliseconds. 1000ms = 1seconds. consider this. Maybe you should increase the time it takes to run the console.clear(), base on your code it executes after 2 and 3 seconds.
#Mr.Buscuit, consider using the setInveral function,
let sec = 0;
setInterval(function () {
console.clear();
console.log(sec);
sec++;
}, 1000);
This log a new number to the log every second. Hope this helps.
1- first line of code you tell your browser to execute that function which print on console number "1"
2- second line you tell browser after 99ms (from beginning of timer) NOT 1099ms clear the console
Why 99ms? because All Timer API(Browser API) e.g (setTimeout, setInterval) works at same time, all of these functions that you do, they have a one(only one) timer, hence that means when timer reach at 1000ms, second setTimeout that you determined its timer with 1099ms reached at 1000ms as well (one timer), hence still 99ms remaining from 1099ms
Summary
Imagine there is one big timer is running for all functions, this means if we have 2 setTimeout with time we specified 1000ms (2 function with same time) this is not means after finish first function that need 1000ms, second starts setTimeout timer that will begin from scratch, hence need 1000ms again with total latency 2000ms, No, this is wrong, two functions will work together
very good resource for understand this concept : Async Concept
I want to write nested timed code with setInterval. I tried the following but no response from browser (Chrome and FF) whatsoever:
setInterval(function() {
console.log('1');
setInterval(function(){
console.log('2');
},5000);
}, 2500);
I expected the above code will wait for two seconds and half before starting, and then log('1'), then wait for five seconds, and log('2'). What happened is that I got no response from both browsers (why?)
Second point, I replaced console.log with window.alert. I got response this time. But not the desired. The first response I get is after 2 seconds and half, second response is after five seconds, but then the two functions start to happen simultaneously.
So, what I want to achieve: Two blocks of code, two different time intervals, and no simultaneous occurrence of both blocks.
In your code an interval is created everytime the "outer" interval runs. In the example below the first interval will be created, and after a timeout of 2500ms the second one will be created.
setInterval(function(){
console.log('1');
}, 2500);
setTimeout(function(){
setInterval(function(){
console.log('2');
}, 5000);
}, 2500);
The behaviour is that your second setInterval is attached to context of the function of the first one.
So when the function of first setInterval end (is cleared), your second which was existing only in context of the function of first one disappear too
EDIT
You can use window.setInterval( /*...*/ ) instead of your second setInterval to make it persist but the behaviour will be that each 2,5 second you create an interval which each 5 second call console.log(2) so you'll get a number of Interval growing which is not what you're asking for.
You may want to use window.setTimeout( /*...*/ ) instead of your second setInterval. The behaviour will be the following :
1 (2.5sec)
1 (5 sec)
1 (7,5sec)
2 (7,5sec) //1st nested
1 (10sec)
2 (10sec) //2nd nested
...
if you want to call this both the operation only once, you are supposed to use setTimeout instead of setInterval.
Check below code:
setTimeout(function() {
console.log('1');
setTimeout(function(){
console.log('2');
},5000);
}, 2500);
this will log "1" after 2.5 sec and "2" after 7.5 sec (i.e. 2.5+ 5.0)
Try using this
var a=0;
setInterval(function() {
if(a==0){
one();
a++;
}
}, 2500);
setInterval(function() {
two();
a=0;
}, 5000);
function one() {
console.log('1');
}
function two() {
console.log('2');
}
Answring from mobile not able to put code in good manner...well use a variable to make run 2500 set interval once ..i am provinding you a bin link...well above code works
In NODEJS I want a function that will keep executing after every 5 seconds, and I used while(1) loop with a time out of 5 seconds. But its not working.
while(1){
var ms=4000;
ms += new Date().getTime();
while (new Date() < ms){}
execute(12345,0);
}
In Javascript you can create some tasks to be called on every interval needed using setInterval:
setInterval(functionToCallOnInterval, intervalInMilliSeconds);
setInterval(function() {
console.log('called about every 5 seconds');
}, 5000);
setInterval(myFunc, 6000);
function myFunc() {
console.log('called about every 6 seconds');
}
Behold
setInterval timing is not accurate so you can't count on this for vital situations.
You should use setInterval instead of WHILE loop.
setInterval(function(){
console.log('test');
},5000);
This 5000 is time in ms!!
The problem with your code is, you are running a thread with infinite execution and thus it will freeze the browser. Instead if you will use setInterval() then a new thread will be run at regular intervals in which your function will be executed. Hope you got the concept well.
I'm trying to make the top row of a table delete itself, every 5 seconds, using javascript. My javascript looks like this:
setTimeout(function(){
document.getElementById("myTable").deleteRow(0);
}, 5000);
which gets it to delete the top row after 5 seconds. Is there a way to reset the setTimeout to begin counting down again?
In this case it looks like you are looking for the functionality of setInterval:
var myTimer = setInterval(function(){
document.getElementById("myTable").deleteRow(0);
}, 5000);
If you would still like to use setTimeout you would want to call another setTimeout inside your function(){ ... }); that does the same thing. Basically have a function that keeps calling itself with a setTimeout like so:
(function loop() {
document.getElementById("myTable").deleteRow(0);
setTimeout(loop, 5000);
})();
Put it inside of a function and call it again.
function deleteRows(){
var t = setTimeout(function(){
document.getElementById("myTable").deleteRow(0);
clearTimeout(t);
deleteRows();
}, 5000);
};
You need to use setInterval instead of setTimeout .
Check the difference between them here: JavaScript Timing Events
setTimeout(function, milliseconds):
Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
Therefor, you can rewrite your code as following:
var timer = setInterval(function(){
document.getElementById("myTable").deleteRow(0);
}, 5000);
Then if you want to stop the execution of that timer function, you can use:
window.clearInterval(timer);
I would use setInterval() instead. Inside your callback function check for number of rows and if the row exists then delete it, if it doesn't remove time interval.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
JS Fiddle example: https://jsfiddle.net/n2yg4fv2/ (I used 1 second delay to make it faster)
Is there any way to call a function periodically in JavaScript?
The setInterval() method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
var intervalId = setInterval(function() {
alert("Interval reached every 5s")
}, 5000);
// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);
See more # setInterval() # MDN Web Docs
Please note that setInterval() is often not the best solution for periodic execution - It really depends on what javascript you're actually calling periodically.
eg. If you use setInterval() with a period of 1000ms and in the periodic function you make an ajax call that occasionally takes 2 seconds to return you will be making another ajax call before the first response gets back. This is usually undesirable.
Many libraries have periodic methods that protect against the pitfalls of using setInterval naively such as the Prototype example given by Nelson.
To achieve more robust periodic execution with a function that has a jQuery ajax call in it, consider something like this:
function myPeriodicMethod() {
$.ajax({
url: ...,
success: function(data) {
...
},
complete: function() {
// schedule the next request *only* when the current one is complete:
setTimeout(myPeriodicMethod, 1000);
}
});
}
// schedule the first invocation:
setTimeout(myPeriodicMethod, 1000);
Another approach is to use setTimeout but track elapsed time in a variable and then set the timeout delay on each invocation dynamically to execute a function as close to the desired interval as possible but never faster than you can get responses back.
Everyone has a setTimeout/setInterval solution already. I think that it is important to note that you can pass functions to setInterval, not just strings. Its actually probably a little "safer" to pass real functions instead of strings that will be "evaled" to those functions.
// example 1
function test() {
alert('called');
}
var interval = setInterval(test, 10000);
Or:
// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);
Old question but..
I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
TaskTimer works both in browser and Node. See documentation for all features.
You will want to have a look at setInterval() and setTimeout().
Here is a decent tutorial article.
yes - take a look at setInterval and setTimeout for executing code at certain times. setInterval would be the one to use to execute code periodically.
See a demo and answer here for usage
Since you want the function to be executed periodically, use setInterval
function test() {
alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
clearInterval(id);
}
The native way is indeed setInterval()/clearInterval(), but if you are already using the Prototype library you can take advantage of PeriodicalExecutor:
new PeriodicalUpdator(myEvent, seconds);
This prevents overlapping calls. From http://www.prototypejs.org/api/periodicalExecuter:
"it shields you against multiple parallel executions of the callback function, should it take longer than the given interval to execute (it maintains an internal “running” flag, which is shielded against exceptions in the callback function). This is especially useful if you use one to interact with the user at given intervals (e.g. use a prompt or confirm call): this will avoid multiple message boxes all waiting to be actioned."