LoginSignup
7
7

More than 5 years have passed since last update.

setTimeoutで、準備が整うまで待機するパターン

Posted at

デモ:

スニペット

/**
 * Repeat setTimeout until callback returns truthy.
 * @param {Function} callback
 * @param {Number} interval
 */
function waitFor(callback, interval) {
    var f = function() {
        if (!callback()) {
            setTimeout(f, interval);
        }
    };
    f();
}

var threshold = 1000;
var startedAt = Date.now();
waitFor(function() {
    var past = Date.now() - startedAt;
    if (past > threshold) {
        console.log('done.');
        return true;
    }
    else {
        console.log('progressing…', past);
    }
}, 100);
7
7
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
7
7