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 = "";
    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;

    //This is supposed to be the id of the current settimeout
    var isTimeoutRunning; 

    button.addEventListener("click", function(event) {
        if (!buttonPressed) {
            buttonPressed = true;
        } else {
            //This should stop the timeout function before scrollImages
            //gets called?
            buttonPressed = false;
        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() {
        cycle += 1;
        scrollImages(cycle, obj);
    }, 2000)

Answers 1

  • You need to define isTimeoutRunning outside your two functions, eg

    var isTimeoutRunning;
    var main = function() {
        // don't redefine isTimeoutRunning here
        // ... etc
    var scrollImages = function(cycle, obj) { ... }

    The problem is that the isTimeoutRunning in scrollImages is defined as global, ie window.isTimeoutRunning. This is a different variable to the one defined in main.

Related Articles