Search code examples
javascripthtmlvariablessettimeouttimedelay

settimeout using a variable input


I want to create a setTimeout with the timeout amount being input by the user.

e.g. I want the user to be able to delay the playback of an audio sample by manually inputting the delay time into a box.

Is it possible to trigger setTimeout from variable input or am I going about this the wrong way?


Solution

  • Yes, you can do this by collecting the number and using it as the timeout variable.

    <input type="number" id="timeout">
    

    Then you can collect it with .value

    var timeout = +document.querySelector("#timeout").value;
    setTimeout(my_function(), timeout);
    

    Remember this is the number of milliseconds, so to make it into seconds multiply timeout by 1000.

    var timeout = +document.querySelector("#timeout").value;
    // convert from milliseconds to seconds
    setTimeout(my_function(), timeout * 1000);
    

    Here is a complete example with seconds.

    function timeout() {
        var milliseconds = +document.querySelector("#timeout").value;
        var seconds = milliseconds*1000;
        setTimeout(() => {
            alert("Timeout has ended");
        }, seconds);
    }
    <input type="number" id="timeout" value="1">
    <button onclick="timeout()">Submit</button>