Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is setTimeout / clearTimeout dangerous?

I wanted to ask if exist a another implementation of setTimeout / clearTimeout to replace this kind of nested structure avoiding the loop back

function timedCount()
{
    document.getElementById('txt').value=c;
    c=c+1;
    t=setTimeout("timedCount()",1000);
}

function stopCount()
{
    clearTimeout(t);
    timer_is_on=0;
}

I have read is too dangerous to have an infinite nested loop, because at an indeterminate moment the client will collapse due the insuficient memory.

I want to ask too What happen with clearTimeout() method? Does it clear the memory stack?

like image 606
Thomas Patrick kairuz Avatar asked Nov 17 '11 10:11

Thomas Patrick kairuz


2 Answers

the "recursive" timeout pattern is definitely not dangerous (nor recursive) by itself but just to be sure use it like this:

function timedCount()
{
    document.getElementById('txt').value=c;
    c=c+1;
    window.t=setTimeout( timedCount, 1000 );
}

function stopCount()
{
    clearTimeout(window.t);
    timer_is_on=0;
}

It is in fact more safe than setInterval because if an error is happening in setInterval call , it just keeps doing it over and over and over again...

(function updatePage(){
throw new Error( "computer is not turned on" );
setTimeout( updatePage, 1000 );
})()

function updatePageDumb(){
throw new Error( "computer is not turned on" );
}

setInterval( updatePageDumb, 1000 );
like image 126
Esailija Avatar answered Sep 24 '22 20:09

Esailija


Why not use setInterval and clearInterval instead?

like image 30
Jonas Høgh Avatar answered Sep 24 '22 20:09

Jonas Høgh