How do I program a D3/json/ajax query which invites new data every 10
seconds.
Here is my first approach for a solution, I think it is not good:
setInterval(function() {
d3.json("http://1.....", function(json) {
....
})
}, 1000);
As it is right or is there a better approach?
Many thanks
For timed execution of a method setInterval is your best option setTimeout could be used but setInterval for this purpose would be better. I would however ensure that your first ajax call has completed before triggering the function again.
Related
I simplified it to better understand what I need: The task that I have to do is, that we have a long unknown nodejs process (with a lot of queued async functions where we never know when they are finished or something like that) and we want to have an update process, that we store current process state in database. For that we have a start up (it stores "start") and a end process that is on top of process.on('beforeExit', function () { ... });. Now we have to handle the "still in running" process that is requested by our customer. For that we want to update the state every ten minutes to running with timestamp (this function already exists and is called state.setRunningState()
Now I have the problem how can I trigger that function every ten minutes. For that I was going the approach to trigger on each event of the working process this function and compares if it is older then 10 minutes ago. Problem is: Some times there are much more time without any event. So second option is setInterval() and here is what my question is about: If I use setInterval my nodejs process will never reach an end, so the process will run endless until Interval is cleared. But I also do never know when I should call clearInterval()
So the Question is: Is there a way to create such a timeout without extending the life time of the nodejs process. If everything is done it should end and ignore the rest of the interval.
Contrary to some of the comments here, this is not a strange requirement to have something executed periodically while the process is running without making the process run infinitely which would make it quite pointless.
There is a built-in mechanism for that. If you don't want your interval (or timeout) to stop the process from exiting then you need to use the .unref() method.
Instead of:
setInterval(() => {
console.log('Interval');
}, 1000);
use:
setInterval(() => {
console.log('Interval');
}, 1000).unref();
and your interval will not stop the process from exiting if there are no other events pending.
Try running this example:
setInterval(() => {
console.log('Interval');
}, 1000).unref();
setTimeout(() => {
console.log('Timeout 1');
}, 3000);
setTimeout(() => {
console.log('Timeout 2');
}, 5000);
See the docs:
https://nodejs.org/api/timers.html#timers_timeout_unref
Let me see if I get this straight.
1- You want to trigger an event every x mins unless if the existing process has ended?
2- You say that node would not quit the process as long as there is a running set interval.
3- you say that since your process runs " lot of queued async functions" you cannot know when the process should end
I think the simplest solution would be to just set another interval to run at a higher frequency and to clear the interval if all functions have returned. Otherwise you might be interested in reading about webworkers
https://www.npmjs.com/package/webworker-threads
This question already has answers here:
javascript interval
(3 answers)
Closed 6 years ago.
I am fairly new to JavaScript, and I am learning it through p5 and videos by Daniel Shiffman.
I've been looking for a way to update a program every minute or so that checks a weather api, so I don't have to refresh the page myself.
I am aware that there are already answers to this question on here, but none of them make sense to me, as I am very new to JS.
So if you could answer it with an ELI5 ("Explain it like I'm five") description that would great.
setInterval() is your easiest option.
Take a look at this simple example:
// Will execute myCallback every 0.5 seconds
var intervalID = window.setInterval(myCallback, 500);
function myCallback() {
// Your code here
}
More information and more examples can be found here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval)
In plain vanilla Javascript, you would use setInterval:
var intervalID = window.setInterval(checkWeatherAPI, 60000);
function checkWeatherAPI() {
// go check API
console.log("checking weather API");
}
If you were to run the above, the callback function: checkWeatherAPI, would run once every minute, or 60,000 milliseconds forever, full documentation here: WindwTimers.setInterval
To stop the interval you would simply run this line:
window.clearInterval(intervalID);
Choosing whether setInterval OR setTimeout is based on your need and requirement as explained a bit about the difference below.
setInterval will be called irrespective of the time taken by the API. For an instance you set an API call every 5 seconds and your API call is taking 6 seconds due to the network latency or server latency, the below setInterval will trigger the second API call before the first API completes.
var timer = setInterval(callAPI, 5000);
function callAPI() {
// TO DO
triggerXhrRequest(function(success){
});
}
Instead, if you want to trigger another API call after 5 seconds once the first API call completed, you can better use setTimeout as below.
var timer = setTimeout(callAPI, 5000);
function callAPI() {
// TO DO
triggerXhrRequest(function(success){
timer = setTimeout(callAPI, 5000);
});
}
setTimeout will be called once after nth seconds. So you can control when the next one can be called as above.
MDN Documentation
setTimeout
setInterval
function doThings() {
// The things I want to do (or increment)
}
setTimeout(doThings, 1000); // Milliseconds
I want to call a function in JavaScript continuously, for example each 5 seconds until a cancel event.
I tried to use setTimeout and call it in my function
function init()
{ setTimeout(init, 5000);
// do sthg
}
my problem is that the calls stops after like 2 min and my program is a little bit longer like 5 min.
How can i keep calling my function as long as i want to.
thanks in advance
The only conceivable explanations of the behavior you describe are that:
As another poster mentioned, init is somehow getting overwritten in the course of executing itself, in the // do sthg portion of your code
The page is being reloaded.
The //do sthg code is going into some kind of error state which makes it looks as if it not executing.
To guarantee that init is not modified, try passing the // do sthg part as a function which we will call callback:
function startLoop(callback, ms) {
(function loop() {
if (cancel) return;
setTimeout(loop, ms);
callback();
}());
}
Other posters have suggested using setInterval. That's fine, but there's
nothing fundamentally wrong with setting up repeating actions using setTimeout with the function itself issuing the next setTimeout as you are doing. it's a common, well-accepted alternative to setting up repeating actions. Among other advantages, it permits the subsequent timeouts to be tuned in terms of their behavior, especially the timeout interval, if that's an issue. If the code were to be rewritten using requestAnimationFrame, as it probably should be, then there is no alternative but to issue the next request within the callback, because requestAnimationFrame has no setInterval analog.
That function is called setInterval.
var interval = setInterval(init, 5000);
// to cancel
clearInterval(interval);
Which way is correct and more efficient in using setInterval() and clearInterval()?
1.
something = setInterval(function() {
try {
...load something
clearInterval(something);
} catch (e) {
// error
}
}, 5000);
2.
something = setInterval(function() {
try {
...load something
} catch (e) {
// error
}
}, 5000);
setTimeout(something, 7000);
EDIT:
For #2, I meant setTimeout() instead of clearInterval().Has been changed.
I assume the interval you're passing into clearInterval is meant to be something.
Your second example will never fire your timer, because you clear the timer immediately after setting it. You're also passing an argument (7000) into clearInterval that won't get used (clearInterval only accepts one argument).
Your first example is right provided that you want to clear the repeated timer at the point where you're calling clearInterval from within the handler. Presumably that's in an if or similar, because if you want a one-off timed callback you'd use setTimeout, not setInterval.
EDIT:
For #2, I meant setTimeout() instead of clearInterval().Has been changed.
That completely changes the question. No, that's not correct. setInterval schedules the function to be called repeatedly on the interval you give it, you don't pass its return value into setTimeout.
If you need something to happen over and over again you use setInterval if you only need it to happen once use setTimeout (you can simulate setInterval by chaining multiple timeouts one after the other). Timeouts only happen once therefore you do no need to clear them. Also clearInterval does not take a time argument so the interval you set will be cleared before it ever executes since classic javascript is synchronous.
just to complete the answer, take many care with setInterval(). if your "...load something" take sometime more time to load than the time according (for a reason or another). it will just don't do it for this time and will wait the next call of setinterval.
I encourage to use setTimeout() as much as possible instead.
You can find find below the use cases that are, according to me, aswering to your questions:
For your case 1:
var something = setInterval(function() {
// Do stuff, and determine whether to stop or not
if (stopCondition) {
clearInterval(something);
}
}, 5000);
For your case 2:
var something = setInterval(function() {
// Do stuff
}, 5000);
// Pass a function to setTimeout
setTimeout(function() {
clearInterval(something);
}, 17000);
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."