Javascript timing problem - javascript

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>

Related

call function periodically in javascript until finished, then start calling different function

I have two functions on my page that I need to call periodically, but in a certain way only.
function_a needs to be run periodically when the page loads, until data is available and downloaded.
After this point, function_b then needs to run periodically forever.
I can easily do...
setInterval(function_a, 1000);
setInterval(function_b, 5000);
But this will run both functions from the start of page load and forever.
How can I stop function_a running once I have determined that it is not needed anymore, and only start function_b running after this point?
I can put checks within the function_a and function_b code so that they dont execute if not needed, but it seems very wasteful to still call them continually when they are not needed.
function_a(){
if (needed) { code here... }
}
function_b(){
if (needed) { code here... }
}
There must be a better way than that?
Instead of a setInterval here, setTimeout will work far better.
function a() {
//do stuff
if(condition) setTimeout(b, 5000)
else setTimeout(a, 1000)
}
function b(){
//do stuff
setTimeout(b, 5000)
}
a()
This way, the function will execute and schedule itself to run again on the desired interval. This is similar to the way requestAnimationFrame is used for creating animations.
You can assign a variable to setInterval() call and use clearInterval()
let a = setInterval(function_a, 1000);
function_b() {
if (a_is_not_needed) { clearInterval(a) }
}
Use clearInterval() to stop a function called in a setInterval()
var needed = false;
var f1 = function(){
console.log("Fct1");
if(needed){
setInterval(f2, 5000); // start f2 when f1 is finish
clearInterval(interval); // stop to call periodically f1
}
}
var f2 = function(){
console.log("Fct2");
}
var interval = setInterval(f1, 1000);
Try this fiddle and open console to see the result

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

Delay jquery function inside the function?

Is it possible to make a function 'idle' for a couple of seconds while it is being executed?
I tried with
setTimeout( function(){
$("#nytLevel").hide();
} , 3000 );
But the rest of the function would just executed.
Below the setTimeout I start a function
function timer(){
myVar = setTimeout( function(){
console.log("SLOW");
} , 10000 );
}
but when 10 seconds have passed it'll console log "SLOW", but it should console log it 13 seconds after because I've put a setTimeout to 3 seconds.
setTimeout() just schedules something to run in the future and the rest of your Javascript continues to run. It does not block further Javascript execution. This is often called an "asynchronous" operation. It runs in the background and will call a callback sometime in the future when it has completed its work. It is also referred to as "non-blocking" because it does not block the rest of your Javascript execution.
Anything you want to not run until the setTimeout() fires must be put inside the setTimeout() callback or called from there.
// define function
function timer(){
myVar = setTimeout(function() {
console.log("SLOW");
}, 10000);
}
// schedule first timer
setTimeout(function() {
$("#nytLevel").hide();
// now start second timer
timer();
}, 3000);
It's worth mentioning that jQuery has a .delay() method that works with animations and other functions put in the queue and it can sometimes streamline your code. In the case above, you could do this:
$("#nytLevel").delay(3000).hide().delay(10000).queue(function(next) {
console.log("SLOW");
next(); // keep the queue moving in case there's something else in the queue
});
Please note that .delay(xxx) only works with jQuery methods that themselves use the queue (such as animations) or with methods you put in the queue yourself using .queue() (as I've shown above).
setTimeout() is an asynchronous function, meaning that code will not pause until the setTimeout() time is completed. If you want code to be delayed along with the setTimeout(), you can put the other code inside of the initial setTimeout()
setTimeout( function(){
$("#nytLevel").hide();
myVar = setTimeout( function(){
console.log("SLOW");
} , 10000 );
} , 3000 );
I wouldn't recommend this, but you could fashion a recursive function to do what you wanted, using a flag to dictate before or after timeout. In the below example you'd call it like this runAfterTimeout() or runAfterTimeout(false)
function runAfterTimeout(run) {
if (! run) {
console.log('about to wait 10 seconds');
setTimeout(function(){runAfterTimeout(true)},10000);
return;
}
console.log('this section runs after 10 seconds');
setTimeout(function(){$("#nytLevel").hide();},3000);
}
Fiddle: https://jsfiddle.net/m9n1xxra/
Bear in mind, timeouts are not 100% accurate. The engine will look for an appropriate break in execution to execute what you want, but if the engine is in the middle of something else, that will execute first.

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)

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

Categories

Resources