猿问

计时器setTimeOut的问题

function getCountDown(elem, countDown) {

if (countDown == 0) {
    elem.attr('disabled', false).html('重新发送');
    clearTimeout(t);    return;
} else {
    elem.attr('disabled', true).html('重新发送(' + countDown + ')');
    countDown--;  var  t = setTimeout(getCountDown(elem, countDown), 1000);
}

}
var countDown = 60;
getCountDown($(this),countDown);
调用大概是这样子,
问题一:
页面上没有从60变到1,而是直接重新发送,但是调试的时候显示了数字的变化;
问题二:
t是undefined,其实setTimeout(getCountDown(elem, countDown), 1000)是有数字的,我调试时发现,但是确无法正确的负值。
问题三:
cuntDown为0时,它又从1开始


陪伴而非守候
浏览 525回答 1
1回答

开满天机

<html><head>&nbsp; &nbsp; <meta charset="utf-8">&nbsp; &nbsp; <script type="text/javascript" src="jquery-2.1.4.min.js"></script>&nbsp; &nbsp; <title>test</title></head><body>&nbsp; &nbsp; <a id="jwtest" href="javascript:;">重新发送</a></body><script type="text/javascript">$(function(){&nbsp; &nbsp; $("#jwtest").click(function(){&nbsp; &nbsp; &nbsp; &nbsp; time($(this));&nbsp; &nbsp; });});var wait=60;function time(o) {&nbsp; &nbsp; if (wait == 0) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; o.html("重新发送");&nbsp; &nbsp; &nbsp; &nbsp; wait = 60;&nbsp; &nbsp; } else {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; o.html("重新发送("+wait+")");&nbsp; &nbsp; &nbsp; &nbsp; wait--;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time(o);&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; 1000);&nbsp; &nbsp; }&nbsp;}</script></html>countDown定义成全局,每次不需要重新传递,每次调用减1,当为0时,再重新赋值60;var t不需要定义,因为setTimeout调用只会执行一次,所以clearTimeout并没有什么作用的
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答