How to pause code execution javascript - 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();

Related

How to stop nested timeOut with same names?

I am trying to use nested timeOut with the same names which is actually works like a loop, not exactly like it.
I try to use this example:
let i = 1;
setTimeout(function run() {
func(i);
setTimeout(run, 100);
}, 100);
from this link.
As you see in this link, I cant use interval and loop.
Here is my actual code:
let i = 0;
let x = setTimeout(async function run() {
if(i == 2) {
// I want to stop my x here completly
console.log(i)
clearTimeout(x);
}
try {
//some code here e.g:
console.log(10)
} catch (err) {
//some other code here e.g:
console.log(err)
}
i++;
x = setTimeout(run, 800);
}, 800);
And my output:
10
10
2
10
10
... //never stops
I also saw this link, but it is not my case.
Could any body please do something so that I can stop x completely?
Thanks in advance.
You need not the timeout reference, because if inside of the function the reference is invalid, because the timeout is called. Then you need to stop just to return.
let i = 0;
setTimeout(async function run() {
if (i == 2) {
console.log(i)
return
}
try {
//some code here e.g:
console.log(10)
} catch (err) {
//some other code here e.g:
console.log(err)
}
i++;
setTimeout(run, 800);
}, 800);
Because when you clearTimeout you don't stop it by return. So your timeout will set another timeout with x = setTimeout(run, 800);. All you need to do is return your clearTimeout(x) to stop your timeout function.
return clearTimeout(x);
In your code, I don't see any reason you need to clear timeout. Timeout run only once time. So if you execute it. It is done.

Cancel an infinite loop in JavaScript

I am trying to timeout a function in case it has an infinite loop. But the below does not work. Any idea why and how to fix it?
setTimeout(clearValues,1000);
function clearValues(){
i=0;
alert("hi "+i);
}
i=19
function infin(){
while(i>0){
console.log(i);
i++;
}
alert("Done");
}
infin();
In the below case, I get the alert displayed ( a bit later than expected ) and the console statements continue printing even after the alert. That means setTimeout did not wait for the loop to end in this case. Any explanation for this?
setTimeout(clearValues,500);
function clearValues(){
alert("clear");
}
function infin(){
for(i=0;i<10000;){
i=i+0.3;
console.log(i);
}
}
infin();
setTimeout works asynchronously, means it will run after 1000ms and the previous event loop is completed. Since the while loop will never be completed, the callback will never be called.
Add a condition to the loop if you want to exit it.
Another solution might be to use interval:
var code = function(){
console.log('tick');
};
var clock = setInterval(code, 200);
When you don't need it anymore:
clearInterval(clock);
It works, when you made the infin call with a slightly different change.
var i = 0;
setTimeout(clearValues, 1000);
var interval = setInterval(infin, 0);
function clearValues() {
out("clear");
clearInterval(interval);
}
function infin() {
if (i < 10000) { // if you be shure that you
i++;
out(i);
} else { // never reach the limit,
clearInterval(interval); // you can remove the four
} // commented lines
}
function out(s, pre) {
var descriptionNode = document.createElement('div');
if (pre) {
var preNode = document.createElement('pre');
preNode.innerHTML = s + '<br>';
descriptionNode.appendChild(preNode);
} else {
descriptionNode.innerHTML = s + '<br>';
}
document.getElementById('out').appendChild(descriptionNode);
}
<div id="out"></div>

How to run through a function again once it reaches the end?

How to run through the loop again once it reaches the last value in the array?
I would like to run the function init() again once its completed because more DOM elements myElement get ajaxed in once they have been clicked on.
I have tried running the init function after the setTimeout but that doesnt work and tried checking for last element on the array with btn.length -1 still doesnt work.
function doSetTimeout(index, btn) {
setTimeout(function() {
jQuery(btn[index]).click();
}, index * 1500);
//init();
}
function init() {
var btn = [].slice.call(document.querySelectorAll('.myElement'));
var index;
for (index = 0; index < btn.length; index++) {
doSetTimeout(index, btn)
}
}
init();
Does this work?
function init() {
var btn = [].slice.call(document.querySelectorAll('.myElement'));
var index = 0;
function click() {
setTimeout(function() {
if(index < btn.length) {
jQuery(btn[index++]).click();
click();
} else {
init();
}
}, 1500);
}
click();
}
If you want to write a "dumb" check based on a timer then use the following idiom:
doWhateverYouHaveToDo();
function doWhateverYouHaveToDo() {
// ...
setTimeout(doWhateverYouHaveToDo, 1500);
}
This will run doWhateverYouHaveToDo approximately every 1.5 seconds, waiting for each invocation to complete before proceeding.

how to pause a jquery while loop with conditional pause length

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

Queueing setTimeout in javascript

I need to flash an element off and on. This works but I don't really like the code. Is there a nice way of doing this?
setTimeout(function(){
toggle();
setTimeout(function(){
toggle();
setTimeout(function(){
toggle();
setTimeout(function(){
toggle();
}, 100);
}, 100);
}, 100);
}, 100);
I'm using jQuery too if that helps.
function toggle_multiple(n)
{
var toggled = 0;
function toggle_one_time()
{
toggle();
toggled += 1;
if (toggled <= n)
setTimeout(toggle_one_time, 100);
}
toggle_one_time();
}
And just call toggle_multiple(4).
A recursive approach:
function multiTimeoutCall (callback, delay, times) {
if (times > 0){
setTimeout(function () {
callback();
multiTimeoutCall (callback, delay, times - 1);
}, delay);
}
}
Usage:
multiTimeoutCall (toggle, 100, 4);
Edit: Yet another approach, without filling the call stack:
function multiTimeoutCall (callback, delay, times) {
setTimeout(function action() { // a named function expression
callback();
if (--times > 0) {
setTimeout (action, delay); // start a new timer
}
}, delay);
}
I could used arguments.callee instead of a named function expression, but seems that it will be deprecated some day in ECMAScript 5...
Why not use setInterval?
var toggler = function() {
if (++self.counter >= self.BLINK_AMOUNT * 2) {
self.counter = 0;
window.clearInterval(self.timer);
return;
}
toggle();
};
toggler.BLINK_AMOUNT = 1;
toggler.counter = 0;
toggler.timer = window.setInterval(toggler, 100);
I can't remember whether or not IE properly implements the self variable in a timer callback - if it doesn't, use a uniquely named global variable instead.
I would use a blinking effect. For jquery there's pulsate, hope that works for you.
Here's yet another version for simplicity:
for (var i= 0; i<4; i++)
setTimeout(toggle, (i+1)*100);
For larger numbers an interval may be more appropriate, but if it's just four toggles multiple timeouts are fine.
Generalizing 'unknown's' idea of using setInterval,
function schedule(fn, max, delay)
{
var counter = 0;
var interval = setInterval(
function()
{
if(counter++ === max)
clearInterval(interval);
fn();
}
, delay);
}
Usage:
schedule(toggle, 4, 100);
If its just flashing that is required, why not use the jQuery animate ? I use the following to direct user attention to messages. But you can do this for any element -
$("#message_box").fadeOut(450).fadeIn(350);
If you want it multiple times, do this -
$("#message_box").fadeOut(450).fadeIn(350).fadeOut(450).fadeIn(350);
You can do like this:
function toggleMany(cnt) {
toggle();
if (--cnt >= 0) window.setTimeout('toggleMany('+cnt+')', 100);
}
toggleMany(4);

Categories