回答編集履歴

3

ローカル変数省略版のサンプルコードを追記

2017/01/13 02:46

投稿

think49
think49

スコア18156

test CHANGED
@@ -112,12 +112,36 @@
112
112
 
113
113
 
114
114
 
115
+ **(2017/01/13 11:45 追記)**
116
+
117
+ 上記コードでは分かりやすいようにローカル変数を使用していますが、それぞれの変数は1回ずつの使用なので変数宣言を省略する事も出来ます。
118
+
119
+
120
+
121
+ ```JavaScript
122
+
123
+ setInterval(function handleCountDown (id) {
124
+
125
+ if (--this.document.getElementById(id).firstChild.data < 1) {
126
+
127
+ location.replace('http://example.com/');
128
+
129
+ }
130
+
131
+ }, 1000, 'counter');
132
+
133
+ ```
134
+
135
+
136
+
115
137
  ### 更新履歴
116
138
 
117
139
 
118
140
 
119
141
  - 2017/01/13 11:35 サンプルコードを追記
120
142
 
143
+ - 2017/01/13 11:45 ローカル変数省略版のサンプルコードを追記
144
+
121
145
 
122
146
 
123
147
  Re: rento さん

2

サンプルコードを更に追記

2017/01/13 02:45

投稿

think49
think49

スコア18156

test CHANGED
@@ -82,4 +82,42 @@
82
82
 
83
83
 
84
84
 
85
+ 関数式にすればグローバル汚染もなくなります。
86
+
87
+ その場合は引数 `id` を排除してもいいですが、設計指針の好みの範疇だと思います。
88
+
89
+
90
+
91
+ ```JavaScript
92
+
93
+ 'use strict';
94
+
95
+ setInterval(function handleCountDown (id) {
96
+
97
+ var textNode = this.document.getElementById(id).firstChild,
98
+
99
+ count = --textNode.data;
100
+
101
+
102
+
103
+ if (count < 1) {
104
+
105
+ location.replace('http://example.com/');
106
+
107
+ }
108
+
109
+ }, 1000, 'counter');
110
+
111
+ ```
112
+
113
+
114
+
115
+ ### 更新履歴
116
+
117
+
118
+
119
+ - 2017/01/13 11:35 サンプルコードを追記
120
+
121
+
122
+
85
123
  Re: rento さん

1

サンプルコードの追記

2017/01/13 02:35

投稿

think49
think49

スコア18156

test CHANGED
@@ -34,4 +34,52 @@
34
34
 
35
35
 
36
36
 
37
+ ### サンプルコード
38
+
39
+
40
+
41
+ - [サンプル - codepen](http://codepen.io/anon/pen/NdrWBR)
42
+
43
+
44
+
45
+ ```HTML
46
+
47
+ <p><span id="counter">5</span>秒後にログインページへ移動します。</p>
48
+
49
+ <ul>
50
+
51
+ <li><a href="https://teratail.com/questions/61815">JavaScript - javascript メソッドがうまく組めない(61815)|teratail</a></li>
52
+
53
+ </ul>
54
+
55
+ <script>
56
+
57
+ 'use strict';
58
+
59
+ function handleCountDown (id) {
60
+
61
+ var textNode = this.document.getElementById(id).firstChild,
62
+
63
+ count = --textNode.data;
64
+
65
+
66
+
67
+ if (count < 1) {
68
+
69
+ location.replace('http://example.com/');
70
+
71
+ }
72
+
73
+ }
74
+
75
+
76
+
77
+ setInterval(handleCountDown, 1000, 'counter');
78
+
79
+ </script>
80
+
81
+ ```
82
+
83
+
84
+
37
85
  Re: rento さん