javascript setInterval not working for object

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>


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


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:

    <li>The this problem</li> </ul>


    It works on every where like thymeleaf etc...

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


  • Linq search text using 'and' operator
  • Add a constant value to all rows in a dataframe
  • Recursive method 10x slower than interative [closed]
  • Resample in a rolling window using pandas
  • How to implement a filter from another stream using RxJava
  • Behaviour of System.Timer when Interval property changed
  • function cannot execute on segment because it accesses relation
  • How can I get new CSRF token in LARAVEL by using ajax
  • MySql - get days remaining
  • data.table replicate rows after join?
  • What is the difference between a “service account” and an “installed application”?
  • Runtime.exec() gives Error: Could not find or load main class
  • How load cv2.KeyPoint and Descriptors correctly on OpenCV 3 with Python 3?
  • Clear fused location provider's location for testing
  • How do I get HTML corresponding to current DOM tree?
  • Limiting recursion to certain level - Duplicate rows
  • JQuery Internet Explorer and ajaxstop
  • JSON response opens as a file, but I can't access it with JavaScript
  • Join two tables and save into third-sql
  • How to model a transition system with SPIN
  • Change an a tag attribute in JavaScript based on screen width
  • Adding custom controls to a full screen movie
  • ORA-29908: missing primary invocation for ancillary operator
  • How to delete a row from a dynamic generate table using jquery?
  • using HTMLImports.whenReady not working in chrome
  • Change div Background jquery
  • How does Linux kernel interrupt the application?
  • Authorize attributes not working in MVC 4
  • EntityFramework adding new object to nested object collection
  • Busy indicator not showing up in wpf window [duplicate]
  • Binding checkboxes to object values in AngularJs
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Converting MP3 duration time
  • Conditional In-Line CSS for IE and Others?
  • Why do underscore prefixed variables exist?
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?