2

I want to write a function that starts a timer if timer does not exists or stop it if that one exists. I mean something like:

(defun toggle-mytimer () 
  (interactive)

  (if (timerp TIMER_NAME)
      (cancel TIMER_NAME)
    ;; else
    (run-with-timer 5 5 'princ "Ciao"))
  )

The run-with-timer docstring says:

This function returns a timer object which you can use in ‘cancel-timer’

but I'm not able to find the object name that would be TIMER_NAME in my function. Where am I doing wrong?

Gabriele Nicolardi
  • 1,199
  • 8
  • 17

1 Answers1

4

You need to keep the timer object in a global variable or closure.

Take global variable for example:

(defvar my/timer nil)

(defun toggle-mytimer () 
  (interactive)
  (if (not (timerp my/timer))
      (setq my/timer (run-with-timer 5 5 'princ "Ciao"))
    (cancel-timer my/timer)
    (setq my/timer nil)))
whatacold
  • 843
  • 6
  • 10