Javascript setTimeout 带参数延迟执行 闭包实现

时间:2021-07-10 04:17:56

 

不是原创,只是 借鉴别人的成果,我在此纪念

1.htm

function GetDateT()
{
var d,s;
d = new Date();
s = d.getFullYear() + "-"; //取年份
s = s + (d.getMonth() + 1) + "-";//取月份
s += d.getDate() + " "; //取日期
s += d.getHours() + ":"; //取小时
s += d.getMinutes() + ":"; //取分
s += d.getSeconds(); //取秒

return(s);

}

function Hello(name)

{

console.log("welcome"+name+" "+GetDateT() );
}

console.log("welcome"+name+" "+GetDateT() );

setTimeout("hello('张三')",5000);

//这个执行肯定没有问题,但是效率不高

 

//我们可以改进一下,采用闭包

2.htm

 


function GetDateT()
{
var d,s;
d = new Date();
s = d.getFullYear() + "-"; //取年份
s = s + (d.getMonth() + 1) + "-";//取月份
s += d.getDate() + " "; //取日期
s += d.getHours() + ":"; //取小时
s += d.getMinutes() + ":"; //取分
s += d.getSeconds(); //取秒

return(s);

}
 
function Hello2(name)
{
console.log("welcome "+name+" "+GetDateT() );
}
function _Hello2(name)
{
return function()
{
return Hello2(name);
};
}
console.log(GetDateT() );
 //_Hello2("张") 是立即执行了,但是它的结果仅返回一个 函数指针,指向Hello2,所以 hello2并没有立即执行(闭包的作用就是扩大的 name变量的作用域)
window.setTimeout(_Hello2("张"),5000);