-1

这是我的代码:

 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;

图像并没有停止在这一点上。下一步应该改变。

4

2 回答 2

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);
于 2017-11-08T22:08:33.087 回答
0

正如其他人所说,这条线:

        timeout = setTimeout(function () {

只是重新创建一个名为 timeout 的变量,而不是创建它的新实例。当你可以做的时候,就是让超时成为一个对象。对象是充当“模板”以创建更多自身实例的函数,因此您实际上将拥有 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;
于 2017-11-08T22:17:08.497 回答