Home > Article > Web Front-end > Everything you need to know about JavaScript timers
Start with an interview question:
JavaScript interview question:Where are the source codes of setTimeout and setInterval implemented? (Not Baidu and Google)
Before reading further, please answer the question in your mind
Your answer may be It would be V8 (or another VM), but unfortunately it's wrong. Although "JavaScript Timers" are widely used, functions like setTimeout
and setInterval
are not part of the ECMAScript specification or any JavaScript engine implementation. The Timer function is implemented by the browser, and the implementation methods of different browsers will be different. At the same time, Timer is also implemented by the Node.js runtime itself.
In the browser, the main timer function is part of the Window
interface, which also has some other functions and objects. This interface makes all its elements globally available within the main JavaScript scope. That's why you can execute setTimeout
directly in the browser's console.
In Node, timers are part of a global
object that behaves like a browser's window
. You can find its implementation in Node's source code.
Some people may think this interview question is bad, but I think you should know this, because if you don't know this, it may indicate that you don't fully understand how V8 (and other VMs) work with The browser interacts with Node.
Here are some examples of timer functions and exercises for coding challenges:
Timer functions are higher-order functions that can be used to delay or repeat Execution of other functions (which take them as first argument).
The following is an example of delayed execution:
// example1.js setTimeout( () => { console.log('Hello after 4 seconds'); }, 4 * 1000 );
This example uses setTimeout
to delay the output of console.log
by 4 seconds. The second parameter of setTimeout
is the delay time in milliseconds. That's why you multiply 4 by 1000. The first parameter of
setTimeout
is the function you want to delay execution.
If you use the node
command to execute the example1.js
file, Node will pause 4. seconds, then prints a line of message, and then exits.
Note that the first parameter of setTimeout
is just a function reference. It is also possible not to use inline functions like example1.js
. The following is the code for the same function without inline functions:
const func = () => { console.log('Hello after 4 seconds'); }; setTimeout(func, 4 * 1000);
If you want a function that uses setTimeout
to delay execution to accept parameters, you can The remaining parameters of setTimeout
itself are used to pass parameter values to the delayed function.
// 函数: func(arg1, arg2, arg3, ...) // 可以用: setTimeout(func, delay, arg1, arg2, arg3, ...)
Here is an example:
// example2.js const rocks = who => { console.log(who + ' rocks'); }; setTimeout(rocks, 2 * 1000, 'Node.js');
The rocks
function above is delayed by 2 seconds, it accepts parameters who
, and setTimeout
The call uses the value "Node.js" for the who
parameter.
Using the node
command to execute example2.js
will print out "Node.js rocks" after 2 seconds.
Now use what you learned earlier about setTimeout
to output the following 2 pieces of content after the required delay time.
Requirements:
You can only define one function, including inline functions. This means that all your setTimeout
calls will have to use the exact same function.
This is my approach:
// solution1.js const theOneFunc = delay => { console.log('Hello after ' + delay + ' seconds'); }; setTimeout(theOneFunc, 4 * 1000, 4); setTimeout(theOneFunc, 8 * 1000, 8);
I have made theOneFunc
receive a delay
parameter, and The value of the delay
parameter is used in the output message. This way the function can output different messages based on the delay value passed to it.
I then used theOneFunc
in two setTimeout
calls, one firing after 4 seconds and the other after 8 seconds. Both setTimeout
calls use the third parameter to represent the delay
parameter of theOneFunc
.
Finally use the node
command to execute the solution1.js
file. The first message will be output after 4 seconds, and the second message will be output after 8 seconds.
What if you are required to output a message every 4 seconds?
Although you can put setTimeout
into a loop, the timer API also provides the setInterval
function, which can meet the requirement of doing something all the time.
The following is an example of setInterval
:
// example3.js setInterval( () => console.log('Hello every 3 seconds'), 3000 );
This example will output a message every 3 seconds. Executing example3.js
with the node
command will cause Node to keep outputting this message until you terminate the process with CTRL C.
Because calling the timer function will plan an action, the action can also be canceled before execution.
调用 setTimeout
会返回一个计时器 ID,可以把计时器 ID 当做参数传给 clearTimeout
函数来取消它。下面一个例子:
// example4.js const timerId = setTimeout( () => console.log('你看不到这行输出!'), 0 ); clearTimeout(timerId);
这个简单的计时器应该在 0
毫秒后被触发(使其立即生效),但实际上并不会,因为此时我们正在获取 timerId
值,并在调用 clearTimeout
之后立即将其取消。
用 node
命令执行 example4.js
时,Node 不会输出任何内容,而程序将会退出。
顺便说一句,在 Node.js 中,还有另一种方法对 0
ms 进行 setTimeout
。 Node.js 计时器 API 还有一个名为 setImmediate
的函数,它与前面 0
毫秒的 setTimeout
基本上相同,但是不用指定延迟时间:
setImmediate( () => console.log('我等效于 0 毫秒的 setTimeout'), );
setImmediate
函数并非在所有浏览器中都可用。千万不要用在前端代码中。
和 clearTimeout
类似,还有一个 clearInterval
函数,除了对 setInerval
的调用外,它们的功能相同,而且也有 clearImmediate
的调用。
在上一个例子中,你可能注意到了,如果用 setTimeout
在 0
毫秒之后执行某个操作,并不意味着会马上执行它(在 setTimeout
这一行之后),而是在脚本中的所有其他内容( clearTimeout
这一行)之后才会执行它的调用。
// example5.js setTimeout( () => console.log('Hello after 0.5 seconds. MAYBE!'), 500, ); for (let i = 0; i < 1e10; i++) { // 同步阻塞 }
在这个例子中定义了计时器之后,我们立即通过一个大的 for
循环来阻塞运行。 1e10
的意思是 1 前面有 10 个零,所以这个循环是 100 亿次循环(基本上模拟了繁忙的 CPU)。在循环时 Node 无法执行任何操作。
当然,这在实际开发中非常糟糕,但是它能帮你了解 setTimeout
延迟是无法保证马上就开始的事实。 500
ms 表示最小延迟为 500
ms。实际上,这段脚本将会执行很长的时间。它必须先等待阻塞循环才能开始。
编写一段脚本,每秒输出一次消息 “Hello World”,但仅输出 5 次。 5 次后,脚本应输出消息 “Done” 并退出。
要求:不能用 setTimeout
。
提示:你需要一个计数器。
这是我的方法:
let counter = 0; const intervalId = setInterval(() => { console.log('Hello World'); counter += 1;if (counter === 5) { console.log('Done'); clearInterval(intervalId); } }, 1000);
把 counter
的值初始化为 0
,然后通过 setInterval
得到其 ID。
延迟函数将输出消息并使计数器加 1。在函数内部的 if
语句中检查现在是否已经输出 5 次了,如果是的话,则输出“Done”并用 intervalId
常数清理。间隔延迟为 1000
毫秒。
当在常规函数中使用 JavaScript 的 this
关键字时,如下所示:
function whoCalledMe() { console.log('Caller is', this); }
在关键字 this
中的值将代表函数的调用者。如果你在 Node REPL 内定义以上函数,则调用方将是 global
对象。如果在浏览器的控制台中定义函数,则调用方将是 window
对象。
下面把函数定义为对象的属性,这样可以看的更加清楚:
const obj = { id: '42', whoCalledMe() { console.log('Caller is', this); } }; // 现在,函数引用为:obj.whoCallMe
现在,当你直接用其引用去调用 obj.whoCallMe
函数时,调用者将是 obj
对象(由其 ID 进行标识):
现在的问题是,如果把 obj.whoCallMe
的引用传递给 setTimetout
调用,调用者将会是谁?
// 将会输出什么? setTimeout(obj.whoCalledMe, 0);
在这种情况下,调用者会是谁?
根据执行计时器函数的位置不同,答案也不一样。在当前这种情况下,根本无法确定调用者是谁。你会失去对调用者的控制,因为计时器只是其中的一种可能。如果你在 Node REPL 中对其进行测试,则会看到调用者是一个 Timetout
对象:
注意,在常规函数中使用 JavaScript 的 this
关键字时这非常重要。如果你使用箭头函数的话,则无需担心调用者是谁。
编写一段脚本,连续输出消息 “Hello World”,但是每次延迟都不一致。从 1 秒开始,然后每次增加 1 秒。即第二次会有 2 秒的延迟,第三时间会有3秒的延迟,依此类推。
如果在输出的消息中包含延迟。预期的输出如下:
Hello World. 1 Hello World. 2 Hello World. 3 ...
要求: 你只能用 const
来定义变量,不能用 let
或 var
。
由于延迟量是这项挑战中的变量,因此在这里不能用 setInterval
,但是可以在递归调用中使用 setTimeout
手动创建执行间隔。第一个使用 setTimeout
执行的函数将会创建另一个计时器,依此类推。
另外,因为不能用 let
和 var
,所以我们没有办法用计数器来增加每次递归调用中的延迟,但是可以使递归函数的参数在递归调用中递增。
下面的方法供你参考:
const greeting = delay => setTimeout(() => { console.log('Hello World. ' + delay); greeting(delay + 1); }, delay * 1000); greeting(1);
编写一段脚本,用和挑战#3 相同的可变延迟概念连续输出消息 “Hello World”,但是这次,每个主延迟间隔以 5 条消息为一组。前 5 条消息的延迟为 100ms,然后是下 5 条消息的延迟为 200ms,然后是 300ms,依此类推。
脚本的行为如下:
在输出的消息中包含延迟。预期的输出如下所示(不带注释):
Hello World. 100 // At 100ms Hello World. 100 // At 200ms Hello World. 100 // At 300ms Hello World. 100 // At 400ms Hello World. 100 // At 500ms Hello World. 200 // At 700ms Hello World. 200 // At 900ms Hello World. 200 // At 1100ms ...
要求: 只能用 setInterval
(不能用 setTimeout
),并且只能用一个 if
语句。
因为只能用 setInterval
,所以在这里需要通过递归来增加下一次 setInterval
调用的延迟。另外还需要一个 if
语句,用来控制在对该递归函数的 5 次调用之后执行该操作。
下面的解决方案供你参考:
let lastIntervalId, counter = 5;const greeting = delay => { if (counter === 5) { clearInterval(lastIntervalId); lastIntervalId = setInterval(() => { console.log('Hello World. ', delay); greeting(delay + 100); }, delay); counter = 0; }counter += 1; };greeting(100);
相关免费学习推荐:js视频教程
The above is the detailed content of Everything you need to know about JavaScript timers. For more information, please follow other related articles on the PHP Chinese website!