setTimeout/clearTimeout是危险的吗?

Tho*_*ruz 5 javascript loops nested infinite settimeout

我想询问是否存在setTimeout/clearTimeout的另一个实现来替换这种嵌套结构,避免回送

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

function stopCount()
{
    clearTimeout(t);
    timer_is_on=0;
}
Run Code Online (Sandbox Code Playgroud)

我读过太危险了,无法拥有无限的嵌套循环,因为在不确定的时刻,客户端会由于内存不足而崩溃.

我想问一下clearTimeout()方法会发生什么?它是否清除了内存堆栈?

Esa*_*ija 4

“递归”超时模式本身绝对不危险(也不递归),但只是为了确保像这样使用它:

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

function stopCount()
{
    clearTimeout(window.t);
    timer_is_on=0;
}
Run Code Online (Sandbox Code Playgroud)

事实上,这比setInterval如果在调用中发生错误更安全setInterval,它只是一遍又一遍地重复......

(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 );
Run Code Online (Sandbox Code Playgroud)