javascript setAttribute 函数

Gor*_*Gor 1 javascript setattribute wait

我的功能有问题setAttribute

这是我的代码

mind.SetRequest(rec_input.value);
mind.Reply();
element.setAttribute('text', mind.GetReply());
element.speak();
Run Code Online (Sandbox Code Playgroud)

element.speak()不等待setAttribute完成。

完成speak()后是否有任何函数可以调用?setAttribute

img.onload = function(){ . . . }加载后调用的函数,img是否有类似的方式可以在加载speak后调用我的函数setAttribute

Max*_*Max 5

尝试这个:

mind.SetRequest(rec_input.value);
mind.Reply();
element.setAttribute('text', mind.GetReply());
setTimeout(function () {
   element.speak();
}, 0);
Run Code Online (Sandbox Code Playgroud)

setAttribute()是同步的,但它是基于 DOM 的方法。这意味着浏览器需要一些额外的处理器滴答来设置该属性。因此,使用超时将代码执行(尝试获取该属性)移至下一个事件循环。