how to pause a jquery while loop with conditional pause length - javascript

I need to pause a while loop for a certain amount of time based on a condition
var i = 2
while (i) {
if (i == 2) {
//pause loop for 5 seconds
//execute function1();
} else {
//pause loop for 4 seconds
//execute function2();
}
}
How could I achieve this.
Thank you

You could do something like this:
var i = 2,
method1 = function() {
//do your thing
start();
},
method2 = function() {
//do your thing
start();
},
start = function() {
if( i && i == 2 ) {
setTimeout(method1,5000);
}
else if( i ) {
setTimeout(method2,4000);
}
}
;
You need to call the start() method at the end of the delayed methods. This way, you avoid a huge number of setTimeout(method1,5000) being called before the 5 seconds is even up.

use the setTimeout() to achieve what you want.
http://www.w3schools.com/jsref/met_win_settimeout.asp

Related

jQuery = Excecute a function every x Seconds while function return false [duplicate]

This question already has answers here:
Repeat code every x seconds but not if [insert check here]
(3 answers)
Do something every 5 seconds and the code to stop it. (JQuery)
(4 answers)
Call a Javascript function every x seconds and stop after y seconds?
(1 answer)
Closed 4 years ago.
Thanks for the attention, and sorry form my very bad english.
I have a nice function using jQuery:
function(){
//do something
if(certain conditions){
return true;
}else{
return false;
}
}
The function work nice... But I need to execute it every X seconds, while the function returns false. If the function returns true, the loop must be stopped.
I have not idea how to do that... Can you help me? Thanks in advance...
you could use an setInterval combined with clearInterval.
var interval = setInterval(function(){
if(certain conditions)
{
// this will prevent the function from running again
clearInterval(interval);
return true;
}
return false;
},1000); // 1000 ms or, 1 sec
You can always use the good old window.setInterval():
var interval = 500;
function callback(){
//your function call here
var result = yourFunction();
//check if we need to clear the timeout
if(result == true){
clearTimeout(handle);
}
}
var handle = setInterval(callback, interval)
Here's a snippet.
var interval = 500;
function callback(){
//your function call here
var result = yourFunction();
//check if we need to clear the timeout
if(result == true){
clearTimeout(handle);
}
}
var handle = setInterval(callback, interval)
function yourFunction(){
document.write(new Date().toLocaleTimeString())
if(Math.random() > 0.2){return false}
else return true;
}
You are looking for the window.setTimeout function.
function yourFunction(){
// do your task
if(1 == 1 /* the condition to make the loop continue*/){
return true;
}else{
return false;
}
}
function loop(){
if(yourFunction()){
window.setTimeout(loop, 1000);
}
}
loop();

Retrieving constantly updating system time in javascript

I want to execute a block of code every two seconds—to accomplish this, I thought the easiest way would be to retrieve the current system time as so:
if ((Date().getSeconds()) % 2 == 0) {
alert("hello"); //I want to add code here!
}
However, my alert is not printing to the screen every two seconds. How can this be properly implemented?
In order to run a block of code every x seconds, you can use setInterval.
Here's an example:
setInterval(function(){
alert("Hello");
}, x000); // x * 1000 (in milliseconds)
Here's a working snippet:
setInterval(function() {
console.log("Hello");
}, 2000);
You can use setInterval(). This will loop every 2 seconds.
setInterval(function() {
//something juicy
}, 2000);
Try using the setInterval() method
setInterval(function () {console.log('hello'); }, 2000)
This should work for you.
setInterval(function() {
//do your stuff
}, 2000)
However, to answer why your code is not working, because it is not in a loop.
runInterval(runYourCodeHere, 2);
function runInterval(callback, interval) {
var cached = new Array(60);
while (true) {
var sec = new Date().getSeconds();
if (sec === 0 && cached[0]) {
cached = new Array(60);
}
if (!cached[sec] && sec % interval === 0) {
cached[sec] = true;
callback();
}
}
}
function runYourCodeHere() {
console.log('test');
}

How to pause code execution javascript

This is my code to run DFS on javascript, I searched and try to use setTimeout to delay each draw for 3 seconds but it won't work. Can someone show me the way to do it?
function DFSWithDirectedGraph(v) {
Nodes[v].visited = true;
reDrawNode(Nodes[v].x, Nodes[v].y, Nodes[v].id, 'blue');
for(var j = 0; j<i; j++) {
if(Path[v][j] != undefined && Nodes[j].visited == false) {
drawArrow(Nodes[v].x, Nodes[v].y, Nodes[j].x, Nodes[j].y, 'blue', Path[v][j]);
DFSWithDirectedGraph(j);
if(Path[j][v] != undefined) {
drawArrow(Nodes[j].x, Nodes[j].y, Nodes[v].x, Nodes[v].y, 'green', Path[j][v]);
} else {
drawArrow(Nodes[j].x, Nodes[j].y, Nodes[v].x, Nodes[v].y, 'green', "");
}
}
}
}
setTimeout(function () { ...your code... }, time_in_milliseconds);
Note that in order to repeatedly call a function after say T milliseconds,
function f(params) {
... do your work ...
id = setTimeout(f, T);
}
f(actual_params);
This will call the function f after every T milliseconds. You can remove the timeout using clearTimeout.
clearTimeout(id); // id returned from the setTimeout function
You should use a different type of loop if you want to accomplish this. A for loop won't pause between each time it loops.
I would do something like this:
var counter = 0;
function step(){
//Do your loop code here
counter++;
if(counter >= {{length of loop}}){
endLoop();
}else{
setTimeout(step, 3000);
}
}
step();

Jquery - looping with nested functions and setInterval()

Probably not the clearest title, but here goes - I need to display two independent countdowns on a page, accepting a user input for the starting value for each. When one reaches zero, the other starts and counts down to zero. Code for this is below, and working as expected.
I call the Timer1 function, which checks a variable for the starting value, if it exists, the count starts. When the count is zero, I clear the interval, reset the display to the starting value, and fire the second timer, if it has a value assigned:
function Timer1() {
var gDuration = goTime;
countdown = setInterval(function () {
if (gDuration >= 0) {
$("#durationValue").html(ToTime(gDuration));
gDuration--;
}
else {
clearInterval(countdown);
$("#durationValue").html(ToTime(goTime));
if (restTime != 0) {
Timer2();
}
}
}, 1000);
}
function Timer2() {
var rDuration = restTime;
countdown = setInterval(function () {
if (rDuration >= 0) {
$("#restValue").html(ToTime(rDuration));
rDuration--;
}
else {
clearInterval(countdown);
$("#restValue").html(ToTime(restTime));
}
}, 1000);
}
The next step is to allow that process to run for a set number of loops - I've tried wrapping setInterval in Timer1 in a for loop, which doesn't work. Any ideas how to better go about this?
for-loops don't work well with asynchronous stuff. Just make it a counter with an end condition as you have demonstrated with g/rDuration already.
With some callback abstractions, and heavy continuation-passing-style:
function timer(el, duration, interval, callback) {
var countdown = setInterval(function() {
if (duration-- >= 0) {
el.text(ToTime(duration));
} else {
clearInterval(countdown);
callback();
}
}, interval);
}
var goTime = …, restTime = …;
function t1(cb) {
timer($("#durationValue"), goTime, 1000, cb);
}
function t2(cb) {
timer($("#restValue"), restTimer, 1000, cb);
}
var loops = …;
(function loop(cb) {
t1(function(){
t2(function() {
if (loop-- >= 0)
loop(cb);
else
cb();
});
});
})(function() {
alert("finished!");
});
The easiest thing I can think of is to have your Timer functions have a parameter with the current iteration. Increment that value whenever one timer starts another time. And use that value to determine if it should indeed start the next timer.

setTimeout First Delay does not take Effect

setTimeout doesn't work as expected because it will execute the codes below subsequently without waiting for the delay to run the first argument of 'setTimeout'
(function() {
var a = ['#bird','#flower','#cat'];
var totalno = settings.imageArray.length;
function rotateImages(start) {
var nextImage = start + 1;
if(nextImage % totalno == 0){
nextImage=0;
}
//do animate here
$(settings.imageArray).fadeOut();
window.setTimeout(function() {
rotateImages(++start % totalno);
}, settings.imageArray[start].delay);
}
rotateImages(0);
})();
Is there a way to write it so that it doesnt fade out right away for the first image?
a simplified version would be :
(function() {
var a = ['#bird','#flower','#cat'];
function rotateImages(start) {
//do something here
window.setTimeout(function() {
rotateImages(++start % a.length;);
}, 1000);
}
rotateImages(0);
})();
it will execute the codes below
subsequently without waiting for the
delay to run the first argument of
'setTimeout'
It looks like you're starting the first rotate directly. Instead of:
rotateImages(0);
Try to start the first rotate with a delay, like:
window.setTimeout(function() {
rotateImages(0);
}, settings.imageArray[0].delay);

Categories