lundi 21 mars 2016

How do I use cleartimeout to stop a recursive settimeout function in .getJSON?

This is the javascript code for a basic website that takes a search term and scrolls though some images of that search term from recent Flickr uploads.

When the user presses the button, it'll start scrolling through the Flickr images, however if he enters another image search and presses the button again, the current image scrolling should stop and it should scroll through images from the new search term.

The problem is that the original scrolling doesn't stop, all it does is overlap the two.

var main = function() {
    var url = "http://ift.tt/1jjjbRY";
    var end = "&format=json&jsoncallback=?";
    var input = document.querySelector("body input");
    var button = document.querySelector("body button");
    var images = document.querySelector("body .images");

    var buttonPressed = false;
    var isTimeoutRunning;

    button.addEventListener("click", function(event) {
        if (!buttonPressed) {
            buttonPressed = true;
            console.log(buttonPressed);
        } else {
            //This should stop the timeout function before scrollImages
            //gets called?
            window.clearTimeout(isTimeoutRunning);
            buttonPressed = false;
            console.log(buttonPressed);
        }
        var value;
        value = input.value;
        $.getJSON((url + input.value + end), function(flickrResponse){
            scrollImages(0, flickrResponse);
        });
    }); 
};

var scrollImages = function(cycle, obj) {
    if (cycle === obj.items.length) {
        console.log("end reached");
        cycle = 0;
    }
    var imgsrc = document.querySelector("body img");
    imgsrc.setAttribute("src", obj.items[cycle].media.m);   

    isTimeoutRunning = setTimeout(function() {
        console.log(isTimeoutRunning);
        cycle += 1;
        scrollImages(cycle, obj);
    }, 2000)
};




Aucun commentaire:

Enregistrer un commentaire