Leahcim
Leahcim

Reputation: 41919

javascript flash message

I have a backbone app that renders announcements into the dom, however, I would like the announcements to disappear after a few seconds. I'm guessing that, after displaying the announcement, I should just call a function that removes it, but is there a way to delay its execution, or to create a callback after I display the template. Sorry if this is an easy question.

   $(this.el).html(this.template({ announcement: announcement}));

     this.removeAnnouncement(); 
  },

  removeAnnounce: function(){
    this.$el.remove();
  }, 

Upvotes: 0

Views: 256

Answers (1)

Marc Baumbach
Marc Baumbach

Reputation: 10473

You can use setTimeout:

window.setTimeout(_.bind(this.removeAnnounce, this), 2000);

This will call this.removeAnnounce after 2000 milliseconds (or 2 seconds). Just note, don't add the () after the this.removeAnnounce as you are actually passing a function reference. The timeout will invoke the function after the time has elapsed.

EDIT: The _.bind portion is making sure the the this in scope is correctly assigned when the timeout calls the function. Thanks @PaulHoenecke

Upvotes: 4

Related Questions