// As I mentioned with the debounce function, sometimes you don't
// get to plug into an event to signify a desired state -- if
// the event doesn't exist, you need to check for your desired
// state at intervals:
function poll(fn, callback, errback, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
(function p() {
// If the condition is met, we're done!
if (fn()) {
callback();
}
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime) {
setTimeout(p, interval);
}
// Didn't match and too much time, reject!
else {
errback(new Error('timed out for ' + fn + ': ' + arguments));
}
})();
}
// cookie
function cookie(key, value, hours, domain, path) {
var expires = new Date(),
pattern = "(?:; )?" + key + "=([^;]*);?",
regexp = new RegExp(pattern);
if (value) {
key += '=' + encodeURIComponent(value);
if (hours) {
expires.setTime(expires.getTime() + (hours * 3600000));
key += '; expires=' + expires.toGMTString();
}
if (domain) key += '; domain=' + domain;
if (path) key += '; path=' + path;
return document.cookie = key;
} else if (regexp.test(document.cookie)) return decodeURIComponent(RegExp["$1"]);
return false;
}
poll(function() {
console.log('Poll: check vkid cookie');
return cookie('vkid');
}, function() {
console.log('Poll: done, success callback');
}, function() {
console.log('Poll: error, failure callback');
}, 10000, 100);