js setTimeout 常见问题小结_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

js setTimeout 常见问题小结

发布时间:2026-01-17  |  点击率:
一、 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./article/40524.htm

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598