import TimeoutError from "./TimeoutError";

function makeTimedCallback(originalCallback, timeout) {
    if (typeof timeout === "undefined") {
        return originalCallback;
    }

    let timer = setTimeout(onTimeout, timeout);

    function onTimeout() {
        timer = null;
        originalCallback.call(originalCallback, new TimeoutError("The call took longer than you wanted!"));
    }

    function callbackWithTimer() {
        if (timer) {
            clearTimeout(timer);
            originalCallback.apply(originalCallback, arguments);
        }
    }

    return callbackWithTimer;
}

export default makeTimedCallback;
