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?

up vote 4 down vote accepted

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)))
  • Welcome! It works. I upvoted your anwer but I'll wait for other hints before mark it as accepted. – Gabriele Nicolardi Dec 6 at 16:27
  • Glad I could help :) – whatacold Dec 7 at 15:17

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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