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?

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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