Javascript setTimeout 带参数延迟执行 闭包实现
不是原创,只是 借鉴别人的成果,我在此纪念
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);
更多相关文章
- css选择在IE中不起作用
- Jquery中动态添加元素的绑定事件不起作用
- JS 模仿块级作用域
- JavaScript中两个感叹号的作用
- 下拉列表中的Prestashop过滤器不起作用
- 带有无线电的JavaScript条件字段不起作用
- 即使在向上滚动时,AngularJS无限滚动调用也会起作用
- 命中输入时,python-mode缩进不起作用
- 由ajax [duplicate]生成时,formset的提交按钮不起作用