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.glzy8.com/article/40524.htm