0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JS:setInterval(setTimeout)の内部で指定した変数をなぜか使用できない。

0
Posted at

初めに

今回、私がjavascriptでコードを書いている際にsetInterval(setTimeout)で躓いたため、本記事に足跡として改善策を記す。
困っている人へ届け。

今回引っかかった点

結果として、私の書いたコード(改変アリ)のbeforeとafterを見ていただきたい。

before


class Hogehoge{
    
    constructor(){
        this.hogestr = "hogehoge";
    }

    //"hogehoge"を表示する関数
    IntervalHoge(){
        console.log(this.hogenum);//setTimeout()でも同じ
    }

    Hogefunc(){
       //一定時間ごとに"hogehoge"と表示する関数
       setInteval(IntervalHoge,1000);
    }

}

これを実行した際にコンソールには、[undefined]と表示された。

after


class Hogehoge{
    
    constructor(){
        this.hogestr = "hogehoge";
    }

    //"hogehoge"を表示する関数(引数を表示するように改変)
    IntervalHoge(hogestr){
        console.log(hogestr);
    }

    Hogefunc(){
       //一定時間ごとに"hogehoge"と表示する関数(三つ目の引数として表示する文字を指定)
       setInteval(IntervalHoge,1000,hogestr);//setTimeout()でも同じ
    }

}

ご覧いただいたように、setInterval(setTimeout)を使用する際には、一定時間での処理に使用する変数でクラスの持っている変数は引数としてsetInterval(setTimeout)に指定してやらねばならない。
複数の引数を指定してやる場合には第3引数以降に「,」で区切って引数を追加してやれば大丈夫だ。  

かなり初歩的なことなのかもしれないが、もしかしたら私以外にもひっかる人間がいるかもしれないのでその助けとなるようにこの場で共有しておく。読んでいただきありがとう。

※かなり初心者のためミスがあったら指摘していただけるとありがたい。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?