Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an elisp piece of code "yield" so emacs doesn't block?

Tags:

emacs

elisp

Is there any way to write something like this without taking over emacs?

(defun dumb-wait (seconds)
    (let ((done (+ (second (current-time)) seconds)))
        (while (< (second (current-time)) done)
            (message "waiting"))))

(dump-wait 5) will block emacs from 5 seconds. Is there anyway to write this so it doesn't block? I just want to be in a loop and check some condition from time to time, and still be able to use emacs.

Thanks!

like image 397
killdash10 Avatar asked Mar 01 '23 06:03

killdash10


1 Answers

(run-at-time time repeat function &rest args) should do it. nil as time means now.

(setq my-timer 
      (run-at-time nil 5 (lambda () (message "waiting")))) ; returns timer object
;; or
(setq my-timer
      (run-at-time nil 5 'message "waiting"))

(cancel-timer my-timer) ; use timer object from above

Edit:

The parameter repeat expects a number as seconds, however there's a function timer-duration, which you can use instead of the number. It returns the number of seconds as provided with a string parameter. This is somewhat easier to read for big intervals.

(timer-duration "3 hours 2 seconds 1 millisec") ; => 10802.001

Possible word you can use are defined in the variable timer-duration-words.

like image 144
andre-r Avatar answered Mar 02 '23 20:03

andre-r