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
Related
I am making a Snake game on my webpage using JavaScript and HTML. In this game I want to call a function after regular time intervals. This function will update and print the position of the snake.
For this I am using setTimeOut(my_function,time).
My code looks like this
function my_function(){
// update values
// display snake
setTimeOut(my_function,time)
}
My question is - Will the above code create a lot of function calls on the function stack like a recursive function. I think it will.
Below is how I think I can optimise it.
function empty_function{
}
while(true){
//update values
//display snake
setTimeOut(empty_function,time)
}
Will this method will also create a lot of function calls on the function stack like a recursive function?
Your optimized solution is actually the one that will crash the program, because it keeps the same function running forever. Your first approach is perfectly fine: setTimeout doesn't call the function immediately but schedules it to be run. In the meantime your process can handle other events and start with a new stack when your function is due to be called.
In your infinite while loop your function will never even be called, as there will never be time for the program to check its scheduled task list.
If your interval is frame based (for example, you wish to update your graphics as often as possible) you might be better off with requestAnimationFrame():
function update(timestamp) {
// render your game
// request this function to be run again on the next frame:
window.requestAnimationFrame(update);
}
window.requestAnimationFrame(update);
As you can see it uses the same approach, but is specifically designed to try and match the refresh rate of the users screen freeing you from having to define the interval between render ticks.
You can achieve this more easily by setInterval.Here is an example;
setTimeout(() => {console.log('this will get printed only once after 1000 ms')}, 1000);
setInterval(() => {console.log('this will get printed after every 1000 ms')}, 1000);
setInterval runs a function again and again after given interval of time.
If you want to stop the setInterval function, this is how you can do it;
let myinterval = setInterval(() => {console.log('Print this again and again after 1000 ms')}, 1000);
// Down here i am clearing the 'myInterval' interval using the 'clearInterval' function.
const clear = () => {
console.log('printing stopped');
clearInterval(myinterval);
}
document.getElementById('stop').addEventListener('click', clear);
<button id='stop'>Stop printing</button>
This question already has answers here:
Why is setTimeout(fn, 0) sometimes useful?
(19 answers)
Closed 3 years ago.
I have a simple question about setTimeout function
My function:
function myFunc(){
// some code here
}
What's different when
I call a function with and without setTimeout:
myFunc();
setTimeout(function(){
myFunc();
}, 0);
Can someone explain help me? Thank you.
setTimeout waits for a given delay then schedules a new task for its callback. This is why setTimeout is logged after script end, as logging script end is part of the first task, and setTimeout is logged in a separate task. Right, we're almost through this, but I need you to stay strong for this next bit…
Tasks are scheduled so the browser can get from its internals into JavaScript/DOM land and ensures these actions happen sequentially. Between tasks, the browser may render updates. Getting from a mouse click to an event callback requires scheduling a task, as does parsing HTML, and in the above example, setTimeout.
https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
setTimeout(,0) will call after all current queue will be finished, and
normal function call goes in the queue first.
You can see here:
function myFunc1(){
console.log("In myFunc1");
}
function myFunc2(){
console.log("In myFunc2");
}
setTimeout(function(){
myFunc1();
}, 0);
myFunc2();
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);
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.
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."