var myTimer = function (callback) { var height = 10; var flag = true; setInterval(function () { if (flag) { height--; if (height <= -10) {flag = false;} } else { height++; if (height >= 10) {flag = true;} } callback(height); }, 200); }; myTimer(function (val) { console.log(val); });