简体   繁体   中英

Merging 2 javascripts into one

I have 2 javascripts working but want to merge them into one. The purpose of the script is to make a checkbox that changes the a varable for the refresh rate.

Script 1 (works as expected)

        window.onload = function () {
    var input = document.querySelector('input[type=checkbox]');

    function check() {
        if (input.checked) {
            var timeout = "10000";
        } else {
            var timeout = "999999";
        }
        document.getElementById('result').innerHTML = 'result ' + timeout;
    }
    input.onchange = check;
    check();
}

<input type="checkbox" value="1" />Checkbox
<br/>
<br/>
<span id="result"></span>

Script 2 (works as expected)

var timeout = 10000; 
var action = function() {
$('#content').load('/arduino/refresh');
}; 
setInterval(action, timeout);

I tought I could just merge them together and let them live happily ever after so I created the following script: (it shows the checkbox but checking/unchecking does not change the refresh rate)

            window.onload = function () {
        var input = document.querySelector('input[type=checkbox]');

        function check() {
            if (input.checked) {
                var timeout = "10000";
            } else {
                var timeout = "999999";
            }
                var action = function() {
    $('#content').load('/arduino/refresh');
    }; 
        }
        input.onchange = check;
        check();
    }
setInterval(action, timeout);

<input type="checkbox" value="1" />Checkbox
<br/>
<br/>
<span id="result"></span>

Any advise?

In the combined script, setInterval is not called within the check event handler. The local variable timeout is modified, but the new value is never used to actually change the refresh rate.

Also, use clearInterval and setInterval together when changing the refresh rate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM