Skip to content

Commit 9d2c24b

Browse files
committed
feat(event-loop): support passing a code string to setTimeout as the callback function
1 parent e50ace8 commit 9d2c24b

File tree

2 files changed

+9
-10
lines changed

2 files changed

+9
-10
lines changed

python/pythonmonkey/builtin_modules/timers.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@ const {
2121
*/
2222
function setTimeout(handler, delayMs = 0, ...args) {
2323
// Ensure the first parameter is a function
24+
// We support passing a `code` string to `setTimeout` as the callback function
2425
if (typeof handler !== "function") {
25-
throw new TypeError("The first parameter to setTimeout() is not a function")
26+
handler = new Function(handler)
2627
}
2728

2829
// `setTimeout` allows passing additional arguments to the callback, as spec-ed

tests/python/test_event_loop.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,13 @@ def to_raise(msg):
4848
pm.eval("clearTimeout(undefined)")
4949
pm.eval("clearTimeout()")
5050

51-
# should throw a TypeError when the first parameter to `setTimeout` is not a function
52-
with pytest.raises(pm.SpiderMonkeyError, match="TypeError: The first parameter to setTimeout\\(\\) is not a function"):
53-
pm.eval("setTimeout()")
54-
with pytest.raises(pm.SpiderMonkeyError, match="TypeError: The first parameter to setTimeout\\(\\) is not a function"):
55-
pm.eval("setTimeout(undefined)")
56-
with pytest.raises(pm.SpiderMonkeyError, match="TypeError: The first parameter to setTimeout\\(\\) is not a function"):
57-
pm.eval("setTimeout(1)")
58-
with pytest.raises(pm.SpiderMonkeyError, match="TypeError: The first parameter to setTimeout\\(\\) is not a function"):
59-
pm.eval("setTimeout('a', 100)")
51+
# passing a `code` string to `setTimeout` as the callback function
52+
assert "code string" == await pm.eval("""
53+
new Promise((resolve) => {
54+
globalThis._resolve = resolve
55+
setTimeout("globalThis._resolve('code string'); delete globalThis._resolve", 100)
56+
})
57+
""")
6058

6159
# making sure the async_fn is run
6260
return True

0 commit comments

Comments
 (0)