up
This commit is contained in:
parent
3defacc09d
commit
f99574f53b
178 changed files with 530 additions and 271 deletions
|
@ -0,0 +1,42 @@
|
|||
|
||||
Using `setInterval`:
|
||||
|
||||
```js run
|
||||
function printNumbers(from, to) {
|
||||
let current = from;
|
||||
|
||||
let timerId = setInterval(function() {
|
||||
alert(current);
|
||||
if (current == to) {
|
||||
clearInterval(timerId);
|
||||
}
|
||||
current++;
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// usage:
|
||||
printNumbers(5, 10);
|
||||
```
|
||||
|
||||
Using recursive `setTimeout`:
|
||||
|
||||
|
||||
```js run
|
||||
function printNumbers(from, to) {
|
||||
let current = from;
|
||||
|
||||
setTimeout(function go() {
|
||||
alert(current);
|
||||
if (current < to) {
|
||||
setTimeout(go, 1000);
|
||||
}
|
||||
current++;
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// usage:
|
||||
printNumbers(5, 10);
|
||||
```
|
||||
|
||||
Note that in both solutions, there is an initial delay before the first output. Sometimes we need to add a line to make the first output immediately, that's easy to do.
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
importance: 5
|
||||
|
||||
---
|
||||
|
||||
# Output every second
|
||||
|
||||
Write a function `printNumbers(from, to)` that outputs a number every second, starting from `from` and ending with `two`.
|
||||
|
||||
Make two variants of the solution.
|
||||
|
||||
1. Using `setInterval`.
|
||||
2. Using recursive `setTimeout`.
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue