Reputation: 775
I made this timer widget that works the way I want, but it locks up the notebook so I can't execute other code cells at the same time.
Here's an example of what I mean:
Any ideas for getting the widget to execute in the background?
In case it helps, here is the code that makes the above widget:
import ipywidgets as widgets
from IPython.display import display, Javascript
from traitlets import Unicode, validate
import time
class Timer(widgets.DOMWidget):
_view_name = Unicode('HelloView').tag(sync=True)
_view_module = Unicode('hello').tag(sync=True)
_view_module_version = Unicode('0.1.0').tag(sync=True)
value = Unicode('00:00:00').tag(sync=True)
def timeit(self, b, limit=180):
#display(self)
hours = 0
mins = 0
secs = 0
for i in range(1,(limit*60+1)):
if i%60 == 0:
if i%3600 == 0:
secs = 0
mins = 0
hours += 1
else:
secs = 0
mins += 1
else:
secs += 1
time.sleep(1)
self.value = '{hour:02}:{minute:02}:{second:02}'.format(hour=hours,minute=mins,second=secs)
def display_timer(timer):
button = widgets.Button(description="Start Timer", button_style='info')
display(button)
display(timer)
button.on_click(timer.timeit)
Upvotes: 0
Views: 3016
Reputation: 775
I found a solution. Read this doc for details.
You use the threading
library to make your update function (in my case the timer that updates every second) run separately so you can still execute other code cells.
Also, I tried doing a couple %%timeit
's on simple test functions like this:
[x*=x for i in range(20)]
And it looks like having this timer widget running in the background didn't cause a significant increase in execution time.
Upvotes: 2