Last active
March 29, 2017 05:35
-
-
Save jiyu3/7075688b9506c0de09e1ca458acf087c to your computer and use it in GitHub Desktop.
[Javascript] ある条件が満たされるまでループする ref: http://qiita.com/jiyu/items/82c8265392b0ac8f9d84
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 読み込み終わると、グローバル変数 MYLIB にライブラリが代入されるものとする --> | |
<script async src="lib.js"> | |
<script> | |
(function loop(args, interval) { | |
if(typeof MYLIB !== "undefined") { // ループを抜ける条件を入れる | |
return MYLIB.func(args); // func(args); return true; などと書いてもいい | |
} | |
setTimeout(loop, interval, args); | |
})([1, 2], 100); // 100ミリ秒ごとにチェックする | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function loop(args, interval) { | |
if(condition) { // ループを抜ける条件を入れる | |
return func(args); | |
} | |
setTimeout(loop, interval, args); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 100ミリ秒毎にライブラリの読み込みが終わったかチェックし、その後関数funcを実行するループを作成する。 | |
* @param {function} func ループを抜ける際に実行される関数 | |
* @param {function} condition ループを抜ける条件。この関数は true か false を返さなければならない | |
* @param {array} args func に適用される引数の配列 | |
* @param {number} interval ループする感覚(ミリ秒) | |
*/ | |
let makeLoop = (func, condition = () => {return true}, args = [], interval = 100) => { | |
(function loop() { | |
if(condition() === true) { | |
return func(args) | |
} | |
setTimeout(loop, interval, args); | |
})(); | |
}; | |
// 読み込み終わると、グローバル変数 MYLIB にライブラリが代入されるものとする | |
$.getScript("lib.js"); | |
let [f, c, a, i] = [ | |
(args) => { MYLIB.func(args) }, // Uncaught ReferenceError を回避するため | |
() => { | |
return typeof MYLIB !== "undefined"; | |
}, | |
[1, 2], | |
100 | |
]; | |
makeLoop(f, c, a, i); // MYLIB に値が代入された後100ミリ秒以内に MYLIB.func([1, 2]) が実行される |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment