setInterval and clearInterval, How to run only 1 time? - javascript

I only want to run the function 1 time.
timerA = setInterval(function()
{
//codes..
clearInterval(timerA);
}, 2000);
I want to call the function inside setInterval only 1 time. How can I do it with setInterval and clearInterval?
Or is there another technique to do it?

Use the setTimeout method if you only want it to run once.
Example:
setTimeout(function() {
// Do something after 5 seconds
}, 5000);

If you only want to run the code once, I would recommend using setTimeout instead:
setTimeout(function(){
//code
}, 2000);
'setInterval' vs 'setTimeout'

Use setTimeout instead:
setTimeout(function() { [...] }, timeout);
this will execute the function only once after timeout milliseconds.

Related

JavaScript Nested setInterval

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

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);

Javascript timing problem

I wont to run a block of code in a certain amount of time and then when done, carry on with another block of code.
Using the setTimeout() is probably what you want. For example...
<script type="text/javascript">
function YourFunction()
{
alert('Hello Stackoverflow');
}
window.setTimeout(YourFunction, 1000);
</script>
Hope it helps
This is how you would do it, using the setTimeout function, which takes code to call as the first argument and how much time it should wait before calling it (in milliseconds) as the second argument:
function callWhenDone() {
// code to call when timeout finishes
}
setTimeout(function() {
// initial code to run
callWhenDone();
}, 5000); // 5000 = run in 5 seconds
Because of the nature of Javascript you have to encapsulate the code you want to run after the timeout is finished in its own function, otherwise it would be run before the timeout is finished. This is, in essense, a callback, and it is a big part of the event-based nature of Javascript.
You'll want to use the setTimeout() function.
setTimeout - executes code after a time interval
clearTimeout - cancels the setTimeout()
More details here.
Use setTimeout.
setTimeout(function() {
// code here
// you can use it recursively
// setTimeout(...);
},
1000 // 1000 miliseconds (= 1 second)
);
and setInterval is like setTimeout, except it repeats a code repeatedly.
<script type="text/javascript">
var timer = setInterval("firstFunction()","1000"); //every second call firstFunction()
var i = 0;
function firstFunction()
{
//first code
i++;
if(i == 3)
{
clearInterval(timer);
secondFunction();
}
}
function secondFunction()
{
//second code
alert("done!");
}
</script>

Categories

Resources