是否JavaScript的功能为块的setInterval返回? [英] Does Javascript's setInterval block for function return?

查看:129
本文介绍了是否JavaScript的功能为块的setInterval返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript函数函数A(),我想每10秒执行。结果
我发现我可以使用的setInterval ,这样我可以这样做: setInverval(一,10000); < BR>
我的问题是:结果
这是否意味着结果
我)每10秒指定的函数被调用(无论是否previous执行运行/多线程的方式)或结果
ii)该函数被调用,当该功能的已完成执行的那么函数下次调用10秒后预定?结果
我在选项2.基本兴趣,如果选项1是默认情况下发生,那么我怎么能实现选项2?

I have a javascript function function a() that I want to be executed every 10 seconds.
I found that I can use the setInterval so that I can do something like: setInverval(a, 10000);
My question is the following:
Does this mean that
i) every 10 seconds the specified function is called (regardless if the previous execution is running/multithreaded way) OR
ii) that the function is called and when this function has finished execution then the next call of the function is scheduled after 10 seconds?
I am basically interested in option 2. If option 1 is what is happening by default then how could I achieve option 2?

推荐答案

基本上,的setInterval 运行,根据选项1,但如果函数花费的时间比间隔时间更,它不会被再次,直到它已完成并达到下一个蜱烧制。例如,如果你有1秒的时间间隔和你的函数需要1.5秒时,它会在2秒钟滴答运行。

Basically, setInterval runs according to option 1, except that if the function takes more than the interval time, it will not be fired again until it has finished and reached the next tick. For example, if you have an interval of 1 second and your function takes 1.5 seconds, it will run on the 2 second tick.

如果你想选择的2(运行X秒功能完成后),调用的setTimeout 在你的函数完成,而不是行为:

If you want the behaviour of option 2 (run X seconds after function completion), call setTimeout at the completion of your function instead:

setTimeout(function a() {
    // your own code
    setTimeout(a, 1000);
}, 1000);

这是如何工作的是,它首先等待1秒,然后调用传递给的setTimeout 的功能。在函数结束时,函数本身( A 是函数的名称)传递给的setTimeout ,然后等待一秒钟来再次调用该函数。这个过程持续到JavaScript的执行被暂停或超时通过使用 clearTimeout

How this works is that it first waits 1 second, then calls the function passed to setTimeout. At the end of the function, the function itself (a is the name of the function) is passed to setTimeout, which then waits another second to call the function again. This continues until JavaScript execution is halted or the timeout is removed by using clearTimeout.

请注意,即使您使用的setInterval ,该函数将的从不的同时运行,由于JavaScript的单线程性质。

Note that even if you use setInterval, the function will never be run concurrently, due to JavaScript's single-threaded nature.

这篇关于是否JavaScript的功能为块的setInterval返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆