Providing code example for Berdir's answer here to give you more information.
Read this article https://www.drupal.org/docs/7/api/batch-api/overview
and check the example module here to checkout the proper way of using the batch processing Drupal 8: https://github.com/GiantRobot/csvimport
you will then know how to alter youyour code to work.
cheers!