javascript setInterval not working for object

吃可爱长大的小学妹 提交于 2019-12-24 00:54:53

问题


SO, I'm trying to create a javascript object, and use the setInterval method.

This doesn't seem to be working. If I remove the quotes, then the method runs once. Any ideas why? Also, I'm using Jquery.

<script>
$(function(){
   var kP = new Kompost();
   setInterval('kP.play()', kP.interval);
});

var Kompost = function()
{
   this.interval = 5000;
   var kompost = this;

   this.play = function()
   {
      alert("hello");
   }
}
</script>

回答1:


Call it like this:

$(function(){
   var kP = new Kompost();
   setInterval(kP.play, kP.interval);
});

The problem is that kP is inside that document.ready handler and not available in the global context (it's only available inside that closure). When you pass a string to setInterval() or setTimeout() it's executed in a global context.

If you check your console, you'll see it erroring, saying kP is undefined, which in that context, is correct. Overall it should look like this:

var Kompost = function()
{
   this.interval = 5000;
   var kompost = this;
   this.play = function() {
     alert("hello");
   };
};

$(function(){
   var kP = new Kompost();
   setInterval(kP.play, kP.interval);
});

You can see it working here




回答2:


The solution provided by @Yacoby and @Nick, will work only if the play method doesn't use the this value inside itself, because the this value will point to the global object.

To handle this you need another approach, for example:

$(function(){
 var kP = new Kompost();
 setInterval(function () {
   kP.play();
 }, kP.interval);
});

See also:

  • The this problem



回答3:


It works on every where like thymeleaf etc...

function load() {
  alert("Hello World!");
}
setInterval(function () {load();}, 10000);


来源:https://stackoverflow.com/questions/3242308/javascript-setinterval-not-working-for-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!