Search code examples
javascriptsettimeoutcleartimeout

clearTimeout does not work proberly


Here is my code:

 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;

The images aren't stopping on this point. There should be changed at the next step.


Solution

  • As others have stated, this line:

            timeout = setTimeout(function () {
    

    Is simply re-creating a variable called timeout, not creating a new instance of it. When you CAN do, is make the timeout an object. Objects are functions that act as a "template" to create more instances of themselves, so you will actually have 1,000 different setTimeout functions.

    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;