您的位置:首页 > Web前端 > JavaScript

js setTimeout 常见问题小结

2013-08-13 11:13 627 查看
一、 setTimeout this指向问题
setTimeout("this.count()",1000)中的this指的是window对象.
js的setTimeout定义为
复制代码 代码如下:
window.setTimeout=function(vCode, iMilliSeconds [, sLanguage]){
//.....代码
return timer//返回一个标记符
}

所以当向setTimeout()传入this的时候,当然指的是它所属的当前对象window了。
解决方法:
1、在调用setTimeout前先保存this,如self=this; setTimeout("self.count()", 1000);
2、使用jquery的$.proxy改变this指向,如$.proxy(setTimeout("this.count()"), this);
二、向setTimeout传入参数
复制代码 代码如下:
function init(){
var url = "<%=basePath%>fetchwater.do?method=searchRealWater&xzqh=" + "<%=xzqh%>" + "&rand="+Math.random();
//alert(url);
window.setTimeout(function(){ searchJDWater(url);},100);
}

亲测可以传入任意参数,可以是string类型也可以是其他的类型,只是在传入this时要注意用上面的解决方法。
附上一个更加详细的向settimeout传参方法链接https://www.geek-share.com/detail/2587323273.html

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js setTimeout