Trying to make a table row that deletes itself - javascript

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)

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

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

setTimeOut() or setInterval() . 4 methods to apply same thing. which is best?

I am displaying a countdown watch with respect to a given endtime.
although its working perfect but i want to know which is best methods to apply.
below is my countdown function.
var timerId;
var postData = {endDate : endDate, tz : tz};
var countdown = function()
{
$.ajax({
type : 'post',
async : false,
timeout : 1000,
url : './ajax_countdown.php',
data : $.param(postData),
dataType : 'json',
success : function (resp){
$('#currentTime').html(resp.remainingTime);
}
});
}
what i want is that function (countdown) shoud be called automatically after every 1 second and if it does not execute/completed within 1 second then cancel the current ajax and start a new ajax call.
now I found there are 4 working methods
method 1: using setInterval() with window object
window.setInterval(countdown, 1000);
method 2 : using setInterval() independently
setInterval(function() {countdown()}, 1000);
method 3 : using setTimeOut inside the function an call other function to intialize main function
var countdown = function() {
$.ajax({ //ajax code });
timerId = setTimeout(countdown, 5000); // assign to a variable
}
function clockStart() {
if (timerId) return
countdown();
}
clockStart(); // calling this function
method 4 : using anonymous function call
var countdown = function() {
$.ajax({ //ajax code });
timerId = setTimeout(countdown, 5000);
}
(function(){
if (timerId) return;
countdown();
})();
Please tell me
What is con and pro of each method and which one is best/right method?
Should i use clearTimeOut() or clearInterval() ?
References
http://javascript.info/tutorial/settimeout-setinterval
Calling a function every 60 seconds
http://www.electrictoolbox.com/using-settimeout-javascript/
I wouldn't use any of your methods. The reason is setTimeout and setInterval do not guarantee that your code will execute after the specified delay. This is because JavaScript is single threaded.
If I need to call a function only once after a specified delay then I use setTimeout. However if I need to call a function after a fixed interval of time then I do not use setInterval. Instead I make use of delta timing. Here's the code.
The advantage of using delta timing is that your code will execute closer to the fixed interval of time you specify. It corrects itself. Creating and using a delta timer is simple. For example your code would be written as follows:
var timer = new DeltaTimer(function (time) {
$.ajax({
// properties
});
if (time - start >= 5000) timer.stop();
}, 1000);
var start = timer.start();
The above delta timer is better than setInterval (method 1), makes use of setTimeout (method 2) but also corrects itself, starts the timer using a function (method 3), and doesn't pollute the scope with a special clockStart function (method 4).
In addition you can easily get the exact time the function is called after the timer starts as the time the function is called is passed as an argument to the function. The timer also has a stop method to stop the timer. To start it again call start again.
Edit:
If you want to make the DeltaTimer look more like setInterval (start the timer automatically) you may implement a spawn function as follows:
DeltaTimer.spawn = function (render, interval) {
var timer = new DeltaTimer(render, interval);
var start = timer.start = function (start) {
return function () {
render.start = start();
};
}(timer.start);
start();
return timer;
};
Then you may automatically create and start the DeltaTimer as follows:
var timer = DeltaTimer.spawn(function countdown(time) {
$.ajax({
// properties
});
if (time - countdown.start >= 5000) timer.stop();
}, 1000);
Thus var timer = DeltaTimer.spawn(funct, delay); is equivalent to var interval = setInterval(funct, delay); and timer.stop(); is equivalent to clearInterval(interval);. I guess that's as much as you can automate it.
The benefit of using #1 over #2 is that the window reference removes the chance of a scope variable overwriting setInterval.
// When out of global scope...
function setInterval() {
}
window.setInterval(foo, 100); // still calls the "correct" setInterval
There's no difference between wrapping the call to countdown in a function (#1, #2). #2 gives you greater flexibility as you can also call other functions/ pass arguments etc (although it's obviously trivial to swap from #1 to #2 if this becomes the case).
#4 saves you having to declare a function clockStart, other than that, it's the same as #3.
Use clearTimeout if you used setTimeout, and clearInterval if you used setInterval...
You should also be aware of how setTimeout and setInterval work differently. There's an amazing answer here which explains that...
As for what I'd use? I'd use #2.
if you are creating countdown then why u don't use jquery plugin and customize it according to your requirements? Checkout here
http://www.tripwiremagazine.com/2012/05/jquery-countdown-scripts.html

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>

stop settimeout in recursive function

my problem is that I can not stop a timer.
I had this method to set a timeout from this forum.
It supposed to store the identifyer in the global variable.
By accident, I found out that it is still running after I hide "mydiv".
I also need to know now, if the recursive function creates multiple instances or just one for the timeouts. Because first I thought that it overwrites "var mytimer" everytime.
Now I am not so sure.
What would be a solid way to stop the timer??
var updatetimer= function () {
//do stuff
setTimeout(function (){updatetimer();}, 10000);
}//end function
//this should start and stop the timer
$("#mybutton").click(function(e) {
e.preventDefault();
if($('#mydiv').is(':visible')){
$('#mydiv').fadeOut('normal');
clearTimeout(updatetimer);
}else{
$('#mydiv').fadeIn('normal');
updatetimer();
}
});
thanks, Richard
I think that most people are getting at the reason why this isn't working, but I thought I would provide you with updated code. It is pretty much the same as yours, except that it assigns the timeout to a variable so that it can be cleared.
Also, the anonymous function in a setTimeout is great, if you want to run logic inline, change the value of 'this' inside the function, or pass parameters into a function. If you just want to call a function, it is sufficient to pass the name of the function as the first parameter.
var timer = null;
var updatetimer = function () {
//do stuff
// By the way, can just pass in the function name instead of an anonymous
// function unless if you want to pass parameters or change the value of 'this'
timer = setTimeout(updatetimer, 10000);
};
//this should start and stop the timer
$("#mybutton").click(function(e) {
e.preventDefault();
if($('#mydiv').is(':visible')){
$('#mydiv').fadeOut('normal');
clearTimeout(timer); // Since the timeout is assigned to a variable, we can successfully clear it now
} else{
$('#mydiv').fadeIn('normal');
updatetimer();
}
});
I think you misunderstand 'setTimeout' and 'clearTimeout'.
If you want to set a timer that you want to cancel later, do something like:
foo = setTimeout(function, time);
then call
clearTimeout(foo);
if you want to cancel that timer.
Hope this helps!
As written mytimer is a function which never has the value of a timeout identifier, therefore your clearTimeout statement will achieve nothing.
I don't see any recursion here at all, but you need to store the value setTimeout returns you, and if you need to pair this with multiple potential events you need to store it against a key value you can lookup - something like an element id perhaps?
This is a simple pseudocode for controlling and conditioning recursive setTimeout functions.
const myVar = setTimeout(function myIdentifier() {
// some code
if (condition) {
clearTimeout(myIdentifier)
} else {
setTimeout(myIdentifier, delay); //delay is a value in ms.
}
}, delay);
You can not stop all the functions that are created, intead of that convert the function to setInterval (represent the same logic that your recursive function) and stop it:
// recursive
var timer= function () {
// do stuff
setTimeout(function (){timer();}, 10000);
}
The same logic using setInterval:
// same logic executing stuff in 10 seconds loop
var timer = setInterval(function(){// do stuff}, 10000)
Stop it:
clearInterval(timer);
As noted above, the main reason why this code isn't working is that you're passingt he wrong thing into the clearTimeout call - you need to store the return value of the setTimeout call you make in updateFunction and pass this into clearTimeout, instead of the function reference itself.
As a second suggestion for improvement - whenever you have what you call a recursive timeout function, you would be better off using the setInterval method, which runs a function at regular intervals until cancelled. This will achieve the same thing you're trying to do with your updateFunction method, but it's cleaner as you only need to include the "do stuff" logic in the deferred function, and it's probably more performant as you won't be creating nested closures. Plus it's The Right way to do it which has got to count for something, right? :-)
(function(){
$('#my_div').css('background-color', 'red');
$('#my_div').hover(function(){
var id=setTimeout(function() {
$('#my_div').css('background-color', 'green');
}, 2000);
var id=setTimeout(function() {
$('#my_div').css('background-color', 'blue');
}, 4000);
var id=setTimeout(function() {
$('#my_div').css('background-color', 'pink');
}, 6000);
})
$("#my_div").click(function(){
clearTimeout(id);
})
})();

Categories

Resources