javascript中的setTimeout与setInterval [英] setTimeout vs setInterval in javascript
本文介绍了javascript中的setTimeout与setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我们可以将setInterval更改为setTimeout函数,它工作正常,我想知道可以使用setTimeout完成
Hi can we change setInterval to setTimeout function, it is working fine I want to know can it is done with 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>
推荐答案
使用函数包含setTimeout,然后在函数内调用
Use a function to contain the setTimeout, and call it within the function
$(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();
})
})
但是,最好在使用clearInterval
后用clearInterval
清除setInterval
:
However it's much better to clear the setInterval
with clearInterval
after you're done with it:
$(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)
})
})
要回答您的问题-是的,您可以用setTimeout
更改setInterval
,对setInterval
所用的代码进行一些细微更改.
To answer your question - yes, you can change setInterval
with setTimeout
with some minor changes to the code you've used for setInterval
这篇关于javascript中的setTimeout与setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文