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

Related

javascript setInterval() collision between the delay and execution time

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

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)

Javascript set/clearinterval is not working

How can i stop a interval in javascript?
why does the interval not stop?
setInterval(alarm, 500);
window.clearInterval(alarm);
also tried:
window.setInterval(alarm, 500);
window.clearInterval(alarm);
always the same problem :(
still doesn't work:
var switc = 1;
getValue();
function getValue (){
if(switc == 1){
var myTimer = window.setInterval(alarm, 500);
}
else if(switc == 0){
window.clearInterval(myTimer);
}
}
function alarm(){
console.log("test");
}
When you call setInterval it returns a integer that you use to cancel the event. Store that into a variable and use that variable to cancel the event.
var myTimer = window.setInterval(alarm, 500);
window.clearInterval(myTimer);
EDIT:
Your code does not work since myTimer is a local variable and is reset every single time you call the function!
Make it global.
var myTimer = null;
function getValue (){
if(switc == 1){
myTimer = window.setInterval(alarm, 500);
}
...
MDN Docs: window.setInterval
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);
where
intervalID is a unique interval ID you can pass to clearInterval().
func is the function you want to be called repeatedly.
code in the alternate syntax, is a string of code you want to be executed repeatedly (using this syntax is not recommended for the same reasons as using eval())
delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.
Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer. If you want to enable this functionality on that browser you must use a compatibility code (see the Callback arguments paragraph).
That code evinces a misunderstanding of the API. The setInterval() function takes two arguments: a function to call, and a number representing the number of milliseconds between calls. The function returns a token (a number) that identifies that particular interval timer. The token can be passed to clearInterval() to cancel the timer.
You are tring to clear an non existent interval. Assign the id returned by setInterval() to an variable and use it in clearInterval().
In your case alarm is the function that executes and its not the intervals id
var interval = setInterval(alarm, 500);
clearInterval(interval);
var timer = setInterval(alarm, 500);
Window.clearInterval(timer);
function alarm() {
// Do stuff
}
You need to save the handle of the interval to a variable so you can reference it later when you want to clear/stop it.

setInterval and clearInterval, How to run only 1 time?

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.

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