繁体   English   中英

执行超时功能后是否有可能注入任何东西

[英]Is there a possibility to inject anything after executing timeout function

例如,我们有这样的代码,

    let a = 0;
    setTimeout(()=>{a++},0);
    console.log(a);

据我了解,超时回调中的所有内容都将在所有调用堆栈函数都将被执行之后执行,然后timeoutCallback才会从“队列”进入执行堆栈。

我的问题:执行超时功能后是否有可能注入任何东西并从超时回调中获取结果? (无需等待所有执行堆栈将为空)

像这样的东西:

    let a = 0;
    setTimeout(()=>{a++},0);
    console.log(a);  // 0
    //some mystery things happened
    console.log(a); // 1

一旦将代码发送到超时队列,您将无法将其从超时队列中取出。 而是将代码移到处理函数中,然后将其发送到超时队列。 然后,您可以将setTimeout保存为变量,稍后可以取消触发超时,然后立即运行该函数。

 let a = 0 function timeoutHandler() { a++ console.log("Counted to " + a) } var timeout = setTimeout(timeoutHandler,10000) clearTimeout(timeout) timeoutHandler() 

执行超时功能后是否有可能注入任何东西

这是安全/不变性问题吗? 因为您对变量a的引用是闭包的示例,并且可以在多个位置进行修改。

 let a = 0; setTimeout(()=>{a++},0); console.log(a); // 0 a++ //some mystery things happened (ie Closures) console.log(a); // 1 

如果您的要求是保持a不受代码其他部分的无意影响,请使用不可变标识符(即const )或使用高阶函数传递增量值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM