JavaScript Nested setInterval - javascript

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

Related

How do I replace the console message without it disappearing so fast?

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

Trying to make a table row that deletes itself

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 run a javascript function by a timer?

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 to wait one second in my for loop javascript?

Ok I have a random dice number generator. and it will have a for loop and inside the loop I am trouble having to figure out how to wait one second like this below.
Loading.
wait one sec
Loading..
wait one sec
...
I can do the rest I just need some help with this.
Use setInterval:
window.setInterval(func, delay[, param1, param2, ...]);
or setTimeout:
setTimeout(function() { }, 1000);
'setInterval' vs 'setTimeout':
setTimeout(expression, timeout); runs the code/function once after the timeout.
setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.
See https://developer.mozilla.org/en/docs/Web/API/window.setInterval
Will call the function at a particular interval
In function foo, you can define all stuff that you need to be executed.
var foo = function{
}
var timeout = setInterval(foo, 1000);
and when you want to stop execution
clearInterval(timeout);
You can either use setTimeout or setInterval :
timer = setTimeout(function(){/*your code here */}, 1000);
or
timer = setInterval(function(){/*your code here */},1000);
and once you would like to clear the timer use :
clearTimeout(timer);
or
clearInterval(timer);

Putting a 10 second pause in xmlHttpRequest submit

This javascript code is fairly lengthy, but the most important part is the end where it posts:
httpwp['send'](paramswp);
I have tried without success to put a 10 second pause between each send. Normally it sends them all instantly.
full code http://pastebin.com/cEM7zksn
To delay 10 seconds before calling this, you could use setTimeout
setTimeout(function() { httpwp['send'](paramswp); }, 10000);
Or more simply:
setTimeout(function() { httpwp.send(paramswp); }, 10000);
The setTimeout() function does not pause execution for the specified time, it queues a function to be executed after the specified time. The line of code after setTimeout() will be executed immediately. So if you have the following code:
1 someFunction();
2 setTimeout(function(){console.log("From timeout");}, 10000);
3 console.log("After setTimeout()");
What will happen is on line 1 someFunction() will be called, then on line 2 an anonymous function will be queued to execute in 10 seconds time, then line 3 will execute, logging "After setTimeout()", and finally 10 seconds later the anonymous function will execute logging "From timeout".
If you want to code a loop where each iteration is spaced out by 10 seconds, rather than using a conventional for loop you write a function that uses setTimeout() to call itself:
// this for loop won't work
for(var i = 0; i < 20; i++) {
// do something
// pause for 10 seconds ---- can't be done
}
// so instead you do something like this:
function timeoutLoop(i, max) {
if (i < max) {
// do something
i++;
setTimeout(function(){timeoutLoop(i, max);}, 10000);
}
}
timeoutLoop(0, 20);
I found your code a little hard to read so I've not tried to integrate the above with it, but here is a really simple demo of the above working: http://jsfiddle.net/CrSEt/1/
Or here is a cleaner version that separates the actual processing from the loop function by using a callback: http://jsfiddle.net/CrSEt/
I'm sure if you play around a bit with the above you'll see how to get it to work in your code. You may want to consider setting subsequent timeouts from inside your ajax success callback.

Categories

Resources