I'm currently trying to automate a date picker, using JavaScript. The date picker contains a header element, displaying the current month and year.

What I'm trying to achieve is a way to continuously click the date picker's "Back" button until the month and year in the header corresponds to the month and year of the given date value.
At first I thought this could be done with a simple while loop, but because while loops freeze all other JavaScript code execution on the page until the loop is finished (and the back button requires JS for navigation), attempting this will simply freeze the page altogether.
Here's the (non-working) code that I've written:
(function() {
function checkDatePickerHeader(selector) {
var date = document.querySelector(selector).innerText;
date = new Date(date);
return date;
}
var datePickerHeaderSelector = "#body > div.daterangepicker.dropdown-menu.opensleft.show-calendar > div.calendar.left > div > table > thead > tr:nth-child(1) > th.month";
var datePickerBackButton = document.querySelector("#body > div.daterangepicker.dropdown-menu.opensleft.show-calendar > div.calendar.left > div > table > thead > tr:nth-child(1) > th.prev.available");
var targetDate = new Date("2016-12-01");
var datePickerDate;
datePickerDate = checkDatePickerHeader(datePickerHeaderSelector);
// click until correct year
while (targetDate.getFullYear() < datePickerDate.getFullYear()) {
datePickerBackButton.click();
// update datePickerDate with new header value
datePickerDate = checkDatePickerHeader(datePickerHeaderSelector);
}
// then click until correct month
while (targetDate.getMonth() < datePickerDate.getMonth()) {
datePickerBackButton.click();
datePickerDate = checkDatePickerHeader(datePickerHeaderSelector);
}
})();
What I've found after investigating is that re-working the while loop(s) into a function and then calling said function with a timeout may work, but I'm unsure of how to repeatedly call the function until the condition has been met.
$('#dateselector').datepicker("setDate", new Date("2016-12-01") );