javascript - 当时的 JavaScript 提高了第二个循环的速度

标签 javascript reload

帮我调试这段代码。该按钮应在单击时打开一个链接,主页上的访问按钮将被禁用,其值将成为一个计时器。第一次点击没有问题,但是当计时器用完并再次点击按钮时,时钟的速度就会加快。请帮我。

<html>
<head>
    <script type = "text/javascript">

    var t;
    var isTimeron = false;
    var counter = 0;
    function disableButt()
    {

    document.getElementById("but1").disabled = true;

    }

    function enableVisit()
    {
        document.getElementById("but1").disabled = false;
    }   

    function stopMe()
    {
        isTimeron = false;
            clearTimeout(t);

    }

    function countdown()
    {
        document.getElementById("but1").value = counter;
        counter--;
        if (counter <= -1)
        {
        stopMe();
        document.getElementById("but1").value = "VISIT";
        document.getElementById("but1").disabled = false;
        enableVisit();
        }
        t = setTimeout("countdown();", 1000);
    }

    function startMe()  {
        if (!isTimeron)
        {
            counter = 10;
            isTimeron = true;
            countdown();    

        }

    }



     </script>
<body>

<a href='' target = '_blank'><input type = "button" id = "but1" value = "VISIT" style="background:#83FF59; font-weight:bold;"
    onclick = "startMe(); disableButt();"/></a>

</body>
</html>

最佳答案

您没有停止第一个计时器。

function countdown()
{
    document.getElementById("but1").value = counter;
    counter--;
    if (counter <= -1)
    {
    stopMe();
    document.getElementById("but1").value = "VISIT";
    document.getElementById("but1").disabled = false;
    enableVisit();
    }
    t = setTimeout("countdown();", 1000);
}

计数器低于零,您通过仍然调用 setTimeout 来调用 stopMe()。您现在有两个计时器正在运行。

直接改成

function countdown()
{
    document.getElementById("but1").value = counter;
    counter--;
    if (counter <= -1)
    {
    stopMe();
    document.getElementById("but1").value = "VISIT";
    document.getElementById("but1").disabled = false;
    enableVisit();
    return;
    }
    t = setTimeout("countdown();", 1000);
}

小建议避免在 setTimeout 中使用字符串。

setTimout(countdown, 1000);

比较好

关于javascript - 当时的 JavaScript 提高了第二个循环的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31106471/

相关文章:

javascript - 如何在不在新选项卡中打开同一页面的情况下使用javascript刷新另一个页面

javascript - 刷新内部包含 JSP 代码片段的 DIV 元素

javascript - Highcharts:获取 x 轴显示图例

javascript - 从 Imgur API 提取数据文件 json 时出现问题

javascript - 不能统一显示网格

python - 之后如何加载redis数据库

swift - 如何重新加载 ui View 的内容 Swift

reactjs - 使用 React 的 Webpack 4 配置

javascript - Rg。 OnWebKitInitialized 未被调用

php - 通过 PHP/Javascript 登录 Wordpress