Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tick(), wait(), normalize(), xhr(), listen() #60

Open
rudiedirkx opened this issue Aug 28, 2017 · 0 comments
Open

tick(), wait(), normalize(), xhr(), listen() #60

rudiedirkx opened this issue Aug 28, 2017 · 0 comments

Comments

@rudiedirkx
Copy link
Owner

rudiedirkx commented Aug 28, 2017

Include alongside ready() and load():

wait = function(ms) {
	return new Promise(function(resolve) {
		setTimeout(resolve, ms || 1);
	});
};

tick = function(callback) {
	var state, ticker, control, t1s, t2s;
	state = {active: true, iteration: 0};
	ticker = function(extra) {
		state.iteration++;
		callback(control);
		state.active && extra !== true && requestAnimationFrame(ticker);
	};
	requestAnimationFrame(ticker);
	t1s = setTimeout(ticker, 1000, true);
	t2s = setTimeout(ticker, 2000, true);
	control = {
		state: state,
		stop: function() {
			state.active = false;
			clearTimeout(t1s);
			clearTimeout(t2s);
		}
	};
	return control;
};

normalize = function(str, limit = 0) {
	str = str.trim().toLowerCase().replace(/[^a-z0-9\-]+/ig, '-').replace(/(^\-+|\-+$)/g, '').replace(/\-+/g, '-');
	if (limit) {
		str = str.split('-').slice(0, limit).join('-');
	}
	return str;
};

xhr = function(method, url, data) {
	return new Promise(function(resolve, reject) {
		var req = new XMLHttpRequest;
		req.open(method, url, true);
		if (method.toUpperCase() == 'POST') {
			req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		}
		req.onload = function(e) {
			resolve(this);
		};
		req.onerror = function(e) {
			reject(this);
		};
		req.send(data);
	});
};

listen = function(targets, callback) {
	var curs;

	if ( targets.constructor != Array ) {
		targets = [targets];
	}

	ready(function() {
		curs = targets.map(fn => fn());
		callback([]);
	});

	tick(function() {
		if ( !curs ) return;

		var news = targets.map(fn => fn());

		var diffs = [];
		curs.forEach((old, i) => {
			if ( old !== news[i] ) {
				diffs.push(i);
			}
		});

		if ( diffs.length) {
// console.log('CHANGES', curs, news);
			callback(diffs);
			curs = news;
		}
	});
};
@rudiedirkx rudiedirkx changed the title tick(), wait(), normalize() tick(), wait(), normalize(), xhr() Dec 26, 2017
@rudiedirkx rudiedirkx changed the title tick(), wait(), normalize(), xhr() tick(), wait(), normalize(), xhr(), listen() Jan 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant