与JavaScript setInterval相关的问题(Questions related to JavaScript setInterval)

编程入门 行业动态 更新时间:2024-10-27 08:35:35
与JavaScript setInterval相关的问题(Questions related to JavaScript setInterval)

我有两个与JavaScript的setInterval()方法相关的问题。 我没有发现任何与这些问题有关的实际案例(但我想这也不是不可能),但出于好奇,我想问这些问题。

1.)如果setInterval()要执行的代码比提供的时间间隔花费的时间多,会发生什么? 先前的执行是否停止,当前的执行是否开始执行,或者两者都将并行运行。

2.)如果整个系统(OS)在调用setInterval()的时间间隔之间挂起怎么办? 在这种情况下,代码是否可以以不同的间隔执行? 我的意思是setInterval()保证代码只能以指定的间隔执行吗? 谢谢

I have two questions related to the JavaScript's setInterval() method. I haven't found any practical cases (but I guess it's not impossible also) related to these question, but for curiosity I wanted to ask these questions.

1.) What happens if the code to be be executed by the setInterval() takes more time than the time interval provided? Does the previous execution stops and the current one starts executing or both will run in parallel.

2.) What if the whole system (OS) is hanged between the time gap when setInterval() is called? Is it possible that the code can execute with some different interval during this condition? I mean does setInterval() guarantees that the code will be executed at the specified interval only? Thanks

最满意答案

JavaScript使用单线程执行。 诸如setTimeout和setInterval函数使许多人相信在JavaScript中可以使用多线程。 实际上, setInterval和setTimeout只是计划在指定时间执行的函数或表达式,并将这些函数添加到同一个单线程堆栈中。 如果在计划触发setTimeout或setInterval时浏览器正在处理其他内容,则只要浏览器可以访问,就会执行计划的函数。

setInterval不保证函数只在指定的时间间隔执行。 setInterval将尝试在指定的时间执行一个函数,但任何数量的事情都可能延迟执行或阻止它完全执行。

JavaScript uses single threaded execution. Functions such as setTimeout and setInterval lead many to believe that it is possible to multi-thread in JavaScript. In reality, setInterval and setTimeout merely schedule a function or expression to execute at a specified time and those functions are added to the same single-threaded stack. If the browser is in the middle of processing something else when a setTimeout or setInterval is scheduled to fire, the scheduled functions will execute as soon as the browser can get to it.

setInterval does not guarantee that a function will execute at the specified interval only. setInterval will try to execute a function at the specified time, but any number of things could delay the execution or prevent it from executing altogether.

更多推荐

本文发布于:2023-07-04 16:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026845.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:setInterval   JavaScript   related   Questions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!