LoginSignup
1
0

More than 5 years have passed since last update.

JavaScriptで秒を数えるいくつかの方法

Last updated at Posted at 2018-10-11

普通の書き方

let i = 0;
const update = () => {
  console.log(i);
  i++;
}
setInterval(update, 1000);

再帰関数

const update = (i = 0) => {
  console.log(i);
  return setTimeout(() => update(i + 1), 1000);
};
update();

クロージャー

const update = () => {
  let i = 0;
  return () => console.log(i++);
};
setInterval(update(), 1000);

短く書くと

const update = (i = 0) => () => console.log(i++);
setInterval(update(), 1000);

Promise

(async() => {
  for (let i = 0; true; i++) {
    await new Promise(res => setTimeout(res, 1000));
    console.log(i);
  }
})();
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0