javascript - 计时器setTimeOut的问题

查看:117
本文介绍了javascript - 计时器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开始

解决方案

<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery-2.1.4.min.js"></script>
    <title>test</title>
</head>
<body>
    <a id="jwtest" href="javascript:;">重新发送</a>
</body>
<script type="text/javascript">
$(function(){
    $("#jwtest").click(function(){
        time($(this));
    });
});
var wait=60;
function time(o) {
    if (wait == 0) { 
        o.html("重新发送");
        wait = 60;
    } else { 
        o.html("重新发送("+wait+")");
        wait--; 
        setTimeout(function() {
            time(o);
        },
        1000);
    } 
}
</script>
</html>

countDown定义成全局,每次不需要重新传递,每次调用减1,当为0时,再重新赋值60;
var t不需要定义,因为setTimeout调用只会执行一次,所以clearTimeout并没有什么作用的

这篇关于javascript - 计时器setTimeOut的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆