Search code examples
javascriptcanvashtml5-canvassetintervalpacman

Can I put a method as the argument in the setInterval function?


Preety straight forward question, though I can't find the answer anywhere I tried these two ways:

setInterval(function(){object/*or this*/.method()},500)

and

setInterval('object/*or this*/.method()',500)

Solution

  • setInterval in fact expects a method as the first argument, though there is an alternative syntax where the first argument can be a string of code (not recommended by most)

    If you're having issues with that code, it may have to do with the scope of 'this'

    setInterval(function(){this.method()},500)
    

    In the above code, 'this' will refer to the closure itself, and wouldn't be the same as 'this.method' occurring outside of that closure. For example, the following would work:

    function MyClass() {
        this.thingy = 'yep this is a thingy'
    }
    var myClass = new MyClass()
    
    // Will log 'MyClass yep this is a thingy'
    setInterval(function() { console.log('MyClass', myClass.thingy) }, 1000)
    

    Whereas the following will not work (presuming instantiating the object and calling foo()):

    function MyOtherClass() {
        this.thingy = 'also a thingy'
    }
    
    // Will log 'MyOtherClass undefined'
    MyOtherClass.prototype.foo = function() {
        setInterval(function() { console.log('MyOtherClass', this.thingy) }, 1000)
    }
    

    The second example will work if we get around using 'this' within the closure (presuming instantiating the object and calling bar()):

    MyOtherClass.prototype.bar = function() {
        var that = this
        setInterval(function() { console.log('MyOtherClass', that.thingy) }, 1000)
    }
    

    Also be sure that setInterval is being passed the name of a function:

    setInterval(someFunction, 500)
    

    rather than executing a function as an argument

    setInterval(someFunction(), 500)
    

    This last line of code is usually a mistake, unless someFunction() returns a function itself ;)