clearTimeout 无法正常工作

clearTimeout does not work proberly

这是我的代码:

 var timeout = 0;

function start() {
    for (var i = 0; i < 1000; i += 50) {
        timeout = setTimeout(function () {
            aRandomNumber1 = random();
            aRandomNumber2 = random();
            aRandomNumber3 = random();

            document.getElementById('field1').innerHTML = '<img src="' + img[aRandomNumber1] + '" alt="Bild1">';
            document.getElementById('field2').innerHTML = '<img src="' + img[aRandomNumber2] + '" alt="Bild2">';
            document.getElementById('field3').innerHTML = '<img src="' + img[aRandomNumber3] + '" alt="Bild3">';
        }, i);
    }

    clearTimeout(timeout);
    timeout = 0;

图片不止于此。应该在下一步更改。

您在每次迭代中都覆盖了对 timeout 的引用,因此您只拥有对上次存储的超时的引用。您可以尝试将所有对超时的引用保存到数组中,例如timeouts,然后遍历数组并清除每个调用的超时;

var timeouts = [];

function start() {
    for (var i = 0; i < 1000; i += 50) {
        var timeout = setTimeout(function () {
            aRandomNumber1 = random();
            aRandomNumber2 = random();
            aRandomNumber3 = random();

            document.getElementById('field1').innerHTML = '<img src="' + img[aRandomNumber1] + '" alt="Bild1">';
            document.getElementById('field2').innerHTML = '<img src="' + img[aRandomNumber2] + '" alt="Bild2">';
            document.getElementById('field3').innerHTML = '<img src="' + img[aRandomNumber3] + '" alt="Bild3">';
        }, i);
       timeouts.push(timeout);
    }
function clearTimeouts(){
   timeouts.forEach(timeout =>{ clearTimeout(timeout);});
   timeouts = [];
}
// stopping all timeouts after 1000 ms
setTimeout(clearTimeouts, 1000);

正如其他人所说,这一行:

        timeout = setTimeout(function () {

只是重新创建一个名为 timeout 的变量,而不是创建它的新实例。当你可以做的时候,就是让超时成为一个对象。对象是充当 "template" 以创建更多自身实例的函数,因此您实际上将拥有 1,000 个不同的 setTimeout 函数。

var timeout = 0;
//Store all created functions
var functions = [];

function start() {
    //Create 1000 objects and store them in the array
    for (var i = 0; i < 1000; i++) {
        functions.push(new Timeout());
    }

    function Timeout() {
        this.timeout = setTimeout(function () {
            aRandomNumber1 = random();
            aRandomNumber2 = random();
            aRandomNumber3 = random();

            document.getElementById('field1').innerHTML = '<img src="' + img[aRandomNumber1] + '" alt="Bild1">';
            document.getElementById('field2').innerHTML = '<img src="' + img[aRandomNumber2] + '" alt="Bild2">';
            document.getElementById('field3').innerHTML = '<img src="' + img[aRandomNumber3] + '" alt="Bild3">';
            }, i);
        }
    }

for (var i = 0; i < functions.length; i++) {
    functions[i].clearInterval(functions[i].timeout);
}

timeout = 0;