The secret to space-dyeing yarn is that dyes only hold fast to fabric when another chemical, called a mordant, is present, and only for as long as it takes the mordant to react with the dye and bond to the fabric. A mordant is the reagent that fixes the color to the yarn. Different color dyes require different mordants: some are metal salts, like copper sulfate, some are organic acids. Once the mordant is used up, the dye will not hold fast to the fabric. This makes it possible to make lengths or spaces of the same strand of yarn different colors.
When dyeing yarn, you work with loose skeins: big loops about a meter or yard long, not the wound-up skeins they sell in stores. When dyeing by hand, you take an enameled steel vat (it looks like a big roasting pan for a turkey, but it's round) and arrange the loops of yarn in a lumpy circle around the bottom of the vat.
I say "lumpy" because, when space-dyeing by hand, the object is not to have all the dyed spaces the some length, but rather to introduce subtle random variations so that the yarn does not make patterns when knitted or woven, but instead produces a "variegated" weave. With machines, it is possible to either deliberately make the spacing precisely the same, to enable pattern weaving, or to deliberately randomize the spacing so that patterns never form. (For example, you would want randomized yarn for mass produced carpeting.)
Then pour different color dyes onto different sections of the loop: these are the "spaces" of space-dyeing. In hand dying, you apply only enough dye and mordant to be absorbed by one section of the skein. You don't let the colors mix together until the mordant has done its job. I'm not sure how they keep the colors separate in a fully automated factory, but they only have to be separate for a short while. Once the chemical process whereby the dye is fixed to the yarn is completed, you can rinse the entire skein in water and let all the colors mix together: all the excess dye washes out.
The yarn is then rinsed, dried, and re-wound into smaller skeins. Since the loops in the re-wound skeins have a different length than the loops when it was taking the dye, when the skeins are wound the colors get all mixed up in the variegated pattern you see in stores.
Node your work.