Skip to main content
 首页 » 编程设计

python之在 Sublime Text 3 API 中使用 set_timeout

2025年05月04日20telwanggs

我正在尝试使用(如标题所示) 设置超时 插件中sublime text 3的功能。
据我了解,在许多情况下需要使用 lambda 函数。所以我尝试了这个简单的测试:

class SetTimeoutTestCommand(sublime_plugin.WindowCommand): 
    def run(self): 
        for x in range(1,10): 
            sublime.set_timeout(lambda : print(x), 4000) 

所以我预计我会一次打印一个数字,每个数字之间有 4 秒的延迟。如 Sublime 3 API 中所述:

Runs the callback in the main thread after the given delay (in milliseconds). Callbacks with an equal delay will be run in the order they were added.

但是我在 4 秒后打印了 9 个“9”。因此,基于循环的第一次迭代,同时打印所有“9”。
您知道我可以做些什么来解决这个问题吗?

提前致谢!

编辑:我发现这个有效(好吧,打印'9'9次,每次之间有1秒的延迟:

class SetTimeoutTestCommand(sublime_plugin.WindowCommand): 
    def run(self): 
        for x in range(1,10): 
            sublime.set_timeout(lambda : print(x), x*1000) 

但问题仍然存在:它只打印出“9”....

请您参考如下方法:

要打印不同的数字,请更改您的插件脚本

class SetTimeoutTestCommand(sublime_plugin.WindowCommand): 
    def run(self, edit): 
        for x in range(1,10): 
            sublime.set_timeout(lambda x=x: print(x), x*1000) 

因为所有 lambda 函数都引用相同的 x 并且当它被执行时 x 值达到 9。