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.
Related
So right now, I am a beginner in coding and I'm having quite a few issues with the setInterval command. What I am trying to do is have a function that decreases a variable by 1 every time 5 seconds pass. However, although I have looked at many different threads with information about the setInterval command, none of them seem to fit my needs (although I may have missed something) and I have been unable to manipulate anything I have seen elsewhere to perform my function.
while (fullness <= 10) {
setInterval(hungry{ fullness--; }, 1000);
}
Why your code is wrong:
//There is no need to loop and call setInterval multiple times
//setInterval will fire the callback function every x milliseconds,
//In your example you have it firing every 1 second(1000 milliseconds)
//while (fullness <= 10) {
//setInterval(hungry{ fullness--; }, 1000);
//}
To fix this:
On page load (document.ready in jquery)
Do just one call to setInterval()
setInterval(function(){
if(fullness <= 10){
hungry{ fullness--; }; //Not sure about this line as it comes from your example
}
}, 5000); //Pass second parameter to setInterval of 5000 milliseconds (5 seconds wait)
You may be trying to use setInterval() in a synchronous way rather than asynchronously.
When you call setInterval(function, period) it only begins a timer that calls the given function every period milliseconds. After calling setInterval javascript will continue to execute the next lines of code right away. If you were to check for your fullness value right after the while loop ends, you might notice it hasn't changed (yet!).
I suggest that you write a new function to handle changing fullness and reacting to the change:
function updateHunger() {
fullness--;
if (fullness < 10) {
//Do something
}
else {
//You have to call clearInterval() to stop the timer
clearInterval(hungerTimer);
}
}
Then use setInterval like this:
//Using a variable to store the timer reference that we create
hungerTimer = setInterval(updateHunger, 5000);
Remember to declare the hungerTimer variable in a scope where it can be accessed from both updateHunger() and the method that calls setInterval().
You have to first set a variable for setInterval and then stop the iteration with clearInterval (important, otherwise the loop will iterate indefinitely). And check for fullness to be greater than 0.
var fullness = 10;
var timer = setInterval(function(){
if(fullness > 0){
fullness--;
}
else{
clearInterval(timer);
}
}, 5000);
Here is the working jsFiddle
The reason you are bumping into this is that JS runs in a single thread. Blocking it by waiting for 1 second would make the entire browser stall, which is why JS does not allow it and we do not have sleep() in JS, we have the Timers API.
But it's nonetheless nice to write straight up for-loops that look synchronous because that's how we "normally" think. That's why you can actually nowadays write something like this if using an engine with async and generator support:
// ES6 features
const sleeper = (x, timeout) =>
new Promise(resolve => setTimeout(resolve, timeout, x));
function* timer(count, timeout) {
for (let i = count; i >= 0; i--) {
yield sleeper(i, timeout);
}
}
async function main() {
for (let i of timer(10, 1000)) {
console.log(await i); // Blocks the main() function but not the JS main thread!
}
}
main();
console.log("The call to main() was non-blocking");
Is there a way to avoid the conflict between the delay and execution time if the time of execution was longer than the delay using setInterval()?
For example:
setInterval(function(){
// some code that takes 300 ms to be executed
// which it's longer than the delay 200 ms
}, 200);
I already found the alternate way, which is to use setTimeout() with recursion to ensure that the delay will start immediately after the function is executed, but my question is about setInterval(), not replacing it with setTimeout()
I'm not sure what is your concern.
Javascript is always single-threaded that means that in time of execution of the function called by setInterval no other function will be executed and no re-run of setInterval may happen!
Naturally if in your setInterval called function you use deferred calls you enable the function to finish and be executed again.
To protect against such problem you may use a simple semaphore like:
var inProcessing = false ;
setInterval(function(){
// some code that takes 300 ms to be executed
// which it's longer than the delay 200 ms
if (!inProcessing){
inProcessing = true ;
$http.get(...).then(function(){inProcessing = false;...},
function(){inProcessing = false;...});
}
}
}, 200);
You cannot do this using setInterval, only setTimeout. If your problem is the lack of easy cancellation of the setTimeout method, you can use the following:
var timeout = setTimeout(function runMe(){
// some code that takes 300 ms to be executed
timeout = setTimeout(runMe, 200);
}, 200);
// somewhere else
clearTimeout(timeout);
You can use a nested setTimeout instead of setInterval. Hope you enjoy !
https://javascript.info/settimeout-setinterval
I'm assuming you just want to postpone a cycle of setInterval if the code from a previous run isn't complete.
var starts = 0;
var ends = 0;
function myFunc () {
starts++;
//doStuff
ends++;
}
setInterval(function () {
if (starts === ends) {
myFunc();
}
}, 200);
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);
I have a list of javascript code like below
javascript: alert("hi1");
javascript: alert("hi2");
javascript: alert("hi3");
javascript: alert("hi4");
...
javascript: alert("hi100")
I want to run 1st line, then wait for a specific time. Then run 2nd line and wait for a specific time. And run 3rd line ...till the end.
Anyone help me?
Thanks!!!
JavaScript is single-threaded and event based. It has an event loop that calls your code, and then nothing else runs until your code returns.
That means that you don't get to "wait" between two statements, because it would still block any other code from running while you wait. Instead you have to schedule a new event at a later time that executes the rest of the code, as a separate function, and then return to the event loop.
Actually, the alert function does block everything until you dismiss the alert, which is one of the reasons it should only be used for really serious problems.
Scheduling something after a specific time is done using the setTimeout function.
Try this to emulate your example:
var counter = 0;
function loop() {
counter += 1;
alert("hi" + counter);
if (counter < 100) {
setTimeout(loop, 1000); // Wait one second (1000 ms), then run again.
}
}
loop();
Here I assumed the time between alerts is always the same (1 second). If it's a simple formula depending on the counter, the example should be easy to modify.
You can also use setInterval to start a repeating timer that fires a timer event at a fixed interval. In this case, I didn't use this because the alert call actually does make everything wait, and we want the timer to only start when the alert is dismissed.
As a side note, there is no need for the "javascript:" in front of your lines. Most likely, you should never have to write "javascript:" anywhere.
Use javascript's setTimeout(function(), time_in_millis);
setTimeout(function(){alert("Hello")}, 3000);
Should do the trick.
You can use:
setTimeout(function(){alert("hi2");}, 3000);
It executes after 3000 milliseconds (waiting time).
split your alerts into functions and use setTimeout before calling the next alert
function partA() {
//line of code you want to execute
window.setTimeout(partB,1000) //wait for a sec
}
function partB() {
//line of code you want to execute
window.setTimeout(partC,1000) //wait for a sec
}
function partC() {
...
}
//repeat
Simply write time-consuming function and use it when you want to pause your script.
function pauseScript(seconds) {
var stop = Date.now() + seconds*1000;
for (var i; stop >= Date.now(); i++){}
}
So your code will look like this
alert("hi1");
pauseScript(10); # wait 10 seconds
alert("hi2");
pauseScript(7); # wait 7 seconds
alert("hi3");
pauseScript(8); # wait 8 seconds
alert("hi4");
// etc...
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."