Search code examples
javascriptjquerybackbone.js

Issue in function invoked by setInterval()


Below is the code snippet from my backbone application. I am getting "Uncaught TypeError: this.toastMsg is not a function" error on running it. But if I directly call the method this.checkUserAction() it is working fine. when I invoke from setInterval() it is throwing that error.

var clock;//Global variable

initialize : function(){
    clock = setInterval(this.checkUserAction,1000);
}

checkUserAction : function(){
    this.toastMsg("Sucess");
},
//Displays message on top of the window
toastMsg : function(msg){
    $(".msgText").text(msg);
    $(".alert").show("slide", { direction: "up"  }, 1000);
}

getting error : Uncaught TypeError: this.toastMsg is not a function


Solution

  • Replace

    clock = setInterval(this.checkUserAction,1000);
    

    With

    var self = this;
    clock = setInterval(function(){self.checkUserAction()},1000);