タイマー処理をストップボタンで止めるという単純なコードなのですが
↓この理屈は分かります。function show()のスコープ内で、
変数timerIdを使ってタイマーを止めています。
let timerId; let i = 0; function show(){ console.log(i); i=i+1; timerId = setTimeout(function(){ show(); },1000); let stop = document.getElementById('stop'); stop.addEventListener('click',function(){ clearTimeout(timerId); }); } show();
でも↓このように、タイマーを止める処理をfunction show()スコープの外に出しても
clearTimeout(timerId);が使えて、タイマー処理を止めることができます。
スコープ内の変数(timerId)はスコープの外では使えないと思うのですが。
実際、変数iは、console.log(i);をスコープの外に出してしまったら使えません。
これはどういう理屈なのでしょうか?よろしくお願いします。
let timerId; let i = 0; function show(){ console.log(i); i=i+1; timerId = setTimeout(function(){ show(); },1000); } show(); let stop = document.getElementById('stop'); stop.addEventListener('click',function(){ clearTimeout(timerId); });
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/15 02:36
退会済みユーザー
2018/12/15 02:38
2018/12/15 02:39
退会済みユーザー
2018/12/15 02:42
2018/12/15 02:48
2018/12/15 02:53
退会済みユーザー
2018/12/15 03:06