I'm having the hardest time wrapping my head around javascript callbacks for some reason and it's causing me a lot of headaches. I have three functions that I'm trying to use to parse some data from a website like so—
function parseText() {
//this finds a bunch of DOM elements, grabs the innerHTML from each and stores
//it in an array
}
function scrollToTop() {
//this scrolls to the top of the window where I'm getting text from,
//which causes the window to load more DOM elements to parse
}
function removeOldElements() {
//this removes the already-parsed DOM elements from the DOM
}
and I've been calling it like this.. which I now realise is a completely horrid method of doing things because as soon as I switch tabs Chrome completely messes with setTimeout
and setInterval
timings and causes a lot of errors..
function doEverything() {
parseText();
setTimeout(scrollToTop, 2000);
setTimeout(removeOldElements, 4000);
}
setInterval(doEverything, 5000);
//this loops it every 5 seconds so I can just run it in a separate tab
//while I continue to work on other things
This works kind of.. but any pause or interruption in setInterval
breaks the code, and I know I should be using callbacks for this kind of thing in order to call one once the first one is done executing, but I just can't seem to get it to work.
I've been reading about callbacks and don't really understand what the format is supposed to be.. I've tried something like this:
function parseText(callback) {
}
function scrollToTop(callback) {
}
function removeOldElements() {
}
function doEverything() {
parseText(
scrollToTop(
removeOldElements
)
)
}
setInterval(doEverything, 5000);
But this only seems to be calling scrollToTop
and then parseText
twice.. and doesn't call the third function at all! What the heck! Now I'm really confused..
Could anyone assist? I'm sure I'm doing something very basic completely wrong here..