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 () 

  (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?


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 () 
  (if (not (timerp my/timer))
      (setq my/timer (run-with-timer 5 5 'princ "Ciao"))
    (cancel-timer my/timer)
    (setq my/timer nil)))
  • Welcome! It works. I upvoted your anwer but I'll wait for other hints before mark it as accepted. – Gabriele Nicolardi Dec 6 '18 at 16:27
  • Glad I could help :) – whatacold Dec 7 '18 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.