for 文
for
文では次のように書けますが、「pause = true
処理」を割り込ませる手段があるのでしょうか。
for
文は同期処理なので割り込めない気がするのですが…。
JavaScript
1'use strict';
2var Sample = (function () {
3 function Sample (max) {
4 this.i = 0;
5 this.pause = false;
6 this.max = max;
7 }
8
9 function handleTimeout (thisArg) {
10 thisArg.pause = false;
11 console.log('pause');
12 thisArg.start();
13 }
14
15 Object.defineProperty(Sample.prototype, 'start', {
16 writable: true,
17 configurable: true,
18 value: function start () {
19 var i = this.i, max = this.max;
20
21 while (!this.pause && i++ < max) {
22 console.log(i);
23 }
24
25 this.i = i;
26
27 if (i < max) {
28 setTimeout(handleTimeout, 1000, this);
29 }
30 }
31 });
32
33 return Sample;
34}())
35
36var sample = new Sample(10000);
37
38setTimeout(function (sample) {
39 sample.pause = true;
40}, 0, sample);
41sample.start();
42setTimeout(function (sample) {
43 sample.pause = true;
44}, 0, sample);
setTimeout
setTimeout
, setInterval
のような非同期処理なら簡単に割り込めます。
'use strict';
var Sample = (function () {
function Sample (max) {
this.i = 0;
this.pause = false;
this.max = max;
}
function handleTimeout (thisArg) {
thisArg.start();
}
function handlePause (thisArg) {
thisArg.pause = false;
console.log('pause');
thisArg.start();
}
Object.defineProperty(Sample.prototype, 'start', {
writable: true,
configurable: true,
value: function start () {
if (this.i++ < this.max) {
if (!this.pause) {
console.log(this.i);
setTimeout(handleTimeout, 0, this);
} else {
setTimeout(handlePause, 1000, this);
}
}
}
});
return Sample;
}());
var sample = new Sample(10000);
sample.start();
setTimeout(function (sample) {
sample.pause = true;
}, 0, sample);
setTimeout Polyfill
setTimeout
の第三引数は IE9- 未対応なので Polyfill を適用してください。
Re: KensukeTsutsumi さん
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。