best way to set an intervalid so I can access later

best way to set an intervalid so I can access later

I have an interval being set in my plugin.  when I want to destroy the plugin I will need to be able to clear the interval.

What would be the best way to access the id?

  1. function($) {
  2.     $.fn.myPlugin = function(options) {
  3.         if (options == 'destroy') {
  4.             // Want to destroy the interval timer here.
  5.             // But how can I access it?
  6.             return;
  7.         }
  8.         return this.each(function() {
  9.             timer = setInterval(function() { foo();}, 1000);
  10.         });
  11.         function foo() {
  12.            // Do some magic
  13.         }
  14.     };
  15. })(jQuery);