2

嗨,我们可以将 setInterval 更改为 setTimeout 函数吗,它工作正常我想知道它可以用 setTimeout 完成吗

<head>
<script type="text/javascript">
$(function() {
    var current = $('#counter').text();
    var endvalue = 50
    $('a').click(function() {
        setInterval(function() {
            if (current === endvalue) {

            } else {
                current++;
                $('#counter').text(current)
            }
        }, 50)
    })
})
</script>
</head>
<body>
<div id="counter">0</div>
<a href="#">Click</a>
</body>
4

4 回答 4

1

使用函数来包含 setTimeout,并在函数内调用它

$(function() {
    var current = $('#counter').text();
    var endvalue = 50;

    function timeoutVersion() {
        if (current === endvalue) {return false;} else {
            current++;
            $('#counter').text(current);
        }
        setTimeout(timeoutVersion, 50);
    }

    $('a').click(function() {
        timeoutVersion();
    })
})​

现场演示| 来源

但是,在完成后清除setIntervalwith会更好clearInterval

$(function() {
    var current = $('#counter').text();
    var endvalue = 50
    $('a').click(function() {
        var storedInterval = setInterval(function() {
            if (current === endvalue) {
                clearInterval(storedInterval);
            } else {
                current++;
                $('#counter').text(current)
            }
        }, 50)
    })
})​

现场演示| 来源


要回答您的问题 - 是的,您可以setInterval通过setTimeout对您使用的代码进行一些小的更改来更改setInterval

于 2012-12-24T14:32:28.870 回答
0

当你使用setInterval()执行一个函数时说,每 1000 毫秒,也就是 1 秒,无论函数执行多长时间,该函数将每 1000 毫秒触发一次,而如果你尝试对 执行相同操作setTimeout(),如果函数正在执行,比如说 500 毫秒,那么执行函数之间的总时间间隔将是 1500 毫秒。

于 2012-12-24T14:40:43.743 回答
0

是的,您可以使用 setTimeout 递归调用相同的函数来获得 setInterval 的效果。请注意,在 setTimeout 中,如果您以递归方式使用它,则必须手动检查以停止循环。但是 setInterval 函数返回一个 id,您可以使用它调用 clearInterval 函数以在需要时停止它。

于 2012-12-24T14:41:41.357 回答
0

我总是推荐使用bobince 更好setTimeoutsetInterval 解释的原因虽然我的答案接近 extramaster 的,但我不提倡使用间隔来清除它。一种更简单的方法是一旦达到目标就不要调用下一次超时

现场演示

 $(function() {
    var current = $('#counter').text();
    var endvalue = 50;

    function increment() {
        if (current !== endvalue) {
            current++;
            $('#counter').text(current)
            setTimeout(increment, 50);
        }

    }

    $('a').click(function() {
        increment();
    })
})​;
于 2012-12-24T14:44:20.093 回答