我是靠谱客的博主 狂野面包,这篇文章主要介绍js setTimeout 常见问题小结,现在分享给大家,希望可以做个参考。

一、 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传参方法链接http://www.uoften.com/article/40524.htm

最后

以上就是狂野面包最近收集整理的关于js setTimeout 常见问题小结的全部内容,更多相关js内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(191)

评论列表共有 0 条评论

立即
投稿
返回
顶部