How to stop nested timeOut with same names? - javascript

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.

Related

clearTimeout does not work in recursive function

I tried to use clearTimeout to escape from the recursive setTimeout function.
But it doesn´t work properly, so I just returned it using if function.
word.move = () => {
if (test >= 10) {
console.log(wodrd.move);
//clearTimeout(word.move);
return;
}
test++;
console.log(test);
word.node.style.top = `${test}px`;
setTimeout(word.move, speed);
};
How could it be stopped by using clearTimeout?
setTimeout returns a value that you need to save, in order to pass to clearTimeout later.
let wordMoveTimeout;
word.move = () => {
if (test >= 10) {
clearTimeout(wordMoveTimeout);
return;
}
// other logic here...
wordMoveTimeout = setTimeout(word.move, speed);
}
Read the documentation on how to use setTimeout here

Stop custom setInterval() function similar to clearInterval() using return variable

I have a custom setInterval function that can modify the interval as it runs. I would like to be able to return a variable that the caller can modify later on. Similar to how clearInterval() works.
Custom Set Interval Function
customSetInterval(callback, interval) {
let stop = false;
this.startInterval(callback, interval, stop);
return stop;
}
startInterval(callback, interval, stop) {
if (stop) {
return;
}
setTimeout(() => {
callback();
interval += 100;
this.startInterval(callback, interval, stop);
}, interval);
}
My current implementation doesn't work because I'm simply returning the value. Not the variable itself. Is it possible to do something like this in JS?
Example Execution
let stop = this.devicewise.customSetInterval(() => {
console.log('HELLO!');
}, 1000);
setTimeout(() => {
console.log('stopping!');
stop = true;
}, 5000);
If this is not possible I plan on creating a boolean hashmap that I add to every time I start. Then create a customClearInterval function to modify that hashmap.
Seems like you wanted a one-time execution with the callback, maybe something like that:
class CustomInterval {
constructor() {
this.id = -1;
}
start(callback, interval) {
console.log(`executing callback in ${interval}ms`);
this.id = setTimeout(() => {
callback();
console.log('callback fired');
}, interval);
}
stop() {
clearTimeout(this.id);
console.log('stopped');
}
}
// ...
let j = new CustomInterval();
j.start(() => {
// do stuff here
}, 5000);
// after some other operations, you decided to cancel the above delayed execution
// no problem.
j.stop();

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

How to get rid of javascript maximum stack size

I need this code to iterate for about 10 seconds (or better indefinitely) without causing javascript maximum stack size. I have comented setInterval because it's causing the problem!
var myToggle = false;
function myFunc () {
setTimeout(function () {
if (myToggle) {
console.log("red");
}
else {
console.log("yellow");
}
myToggle = !myToggle;
}, 500);
// setInterval(myFunc, 10000);
}
myFunc();
Call setInterval instead. setTimeout will call the inner function once. setInterval will continue calling until you cancel.
This usually a sign of bad design but the solution may be the following:
var myToggle = false;
function myFunc () {
var startTime = new Date()/1;
function wait () {
if (myToggle) {
console.log("red");
} else {
console.log("yellow");
}
myToggle = !myToggle;
if (new Date() < startTime + (10*1000)) { // exit condition
setTimeout(wait, 500);
}
}
wait();
}
myFunc();
FYI: Infinite callbacks, among the other things, slowdown the browser and consume battery on mobile devices.

Categories