setTimeout 学习笔记

    xiaoxiao2023-03-24  1

    文章参考 

    http://developer.51cto.com/art/201105/265945.htm

     

     

    1、简单调用方法

    function hello() { alert("hello"); } //没有引号,直接饮用函数名,没有括号 window.setTimeout(hello, 3000); //有引号,直接引用函数名,带括号 window.setTimeout("hello()", 3000); //直接添加匿名函数 window.setTimeout(function(){ alert(111); },3000);

     

    2、传递参数

    2.1 问题例子

    //setTimeout传递参数 var count = 10; function testParam(param){ alert("param : " + param); } //会立马执行testParam()方法,而不会等待3000毫秒 window.setTimeout(testParam(count),3000);

     

    2.2 解决办法

    //根据用户名显示欢迎信息 function hello(_name) { alert("hello," + _name); } //创建一个函数,用于返回一个无参数函数 function _hello(_name) { alert("_name : " + _name); return function () { hello(_name); } } var userName = "huangbiao"; //会立马执行hello()方法,然后过3000毫秒之后,再执行下面的匿名方法,该方法就是调用hello(_name)方法, // return function () { // hello(_name); // } window.setTimeout(hello(userName), 3000);

     

     

    3、递归的解决办法

    //使用setTimeout方法递归 var i=0; function xilou(){ i+=1; if(i>10){alert(i);return;} setTimeout("xilou()",1000); //用这个也可以 //setTimeout(xilou,1000); }

     

    实战——获取验证码,下面代码是我在网上copy的

     

    //获取验证码 var wait=60; function identiCode(o) { //判断用户是否输入了手机号 if(!checkMobile(document.getElementById("phoneNumberId"))){ alert("请先输入手机号码"); document.getElementById("phoneNumberId").focus(); return false; } var currentObj = $(o); if (wait == 0) { currentObj.html("获取验证码"); wait = 60; } else { currentObj.html("重新发送(" + wait + ")"); wait--; setTimeout(function() { identiCode(o); }, 1000); } }

     

     

     

    转载请注明原文地址: https://ju.6miu.com/read-1200232.html
    最新回复(0)