This article mainly introduces the scope issues in timers in js. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
/* 各种运动 */ function Animation(){}; Animation.prototype={ /* 匀速运动 */ linear:function(obj,target){ obj.timer=null; clearInterval(obj.timer); var step=obj.offsetLeft<target?5:-5;//用位置来判断运动的方向 if(obj.offsetLeft!=target){ obj.timer=setInterval(function(){ var res=target-obj.offsetLeft;//核心好代码 当运动到指定位置的时候差值不会超过5 来作为停止运动的条件 if(Math.abs(res)<=Math.abs(step)){ obj.style.left=target+"px"; clearInterval(obj.timer); } else{ obj.style.left=obj.offsetLeft+step+"px"; } } ,1000/60); } }, /* 循环往复运动 */ loop:function(obj,target){ var timer=null; clearTimeout(timer); var fn=arguments.callee.bind(this);//绑定this指向 if(obj.offsetLeft==target){ this.linear(obj,0); } else if(obj.offsetLeft==0){ this.linear(obj,target); } /* 定时器的作用域是全局作用域 在里面调用的函数都是全局作用域下调用的 */ timer=setTimeout(function(){ fn(obj,target); },900); } } var animation=new Animation(); 刚开始我没有绑定fn的this指向的时候 一直报错
I was thinking what was going on. The function is obviously defined in Animation and the method is also called by it. So this should point to Animation.
So I continued to look down and saw
##Oh, I understand setTimeout and setInterval
Generally it is written like this
timer=setTimeout(function(){},1000/60);
A closure is formed. The scope of the ordinary function in the closure is window
, so if fn is executed under window, then this is window
And linear is defined in Animation, so the function cannot be found and an error is reported
It doesn’t matter if the scope of the fn function is bound to Animation
var fn=arguments.callee.bind(this); 当调用loop的时候 this指的就是Animation 如果没明白 我再举一个简单的例子 var obj={ age:"17; } setInterval(function(){ console.log(this.age); }.bind(obj),1000);
Analysis of DOM objects in JavaScript
How to solve the angular paging plug-in tm. The problem of secondary triggering of pagination
The above is the detailed content of About the scope problem in timer in js. For more information, please follow other related articles on the PHP Chinese website!