Question

I have play and skip buttons for JSON array working fine:

jQuery:

$(function() {
    // Fetch the initial image
    fetchImage(index);

    // Event listeners
    $("#play").click(function() { fetchImage(next); setInterval(function() { fetchImage(next); }, 1000); return false;});
    $("#stop").click(function() { clearInterval(xxx); return false;});
    $("#prev").click(function() { fetchImage(prev); return false;});
    $("#next").click(function() { fetchImage(next); return false;});
});

xxx should preferably be a variable I read. setInterval() returns a value. I've read several examples. I have not been successful.

Test page: http://flamencopeko.net/icons_cogo_16.php

JSON thing: http://flamencopeko.net/icons_ajax.php

Source: http://flamencopeko.net/icons_cogo_16.txt

Source: http://flamencopeko.net/icons_ajax.txt

Was it helpful?

Solution

You have to name your interval first to be able to clear it. Here's what I would do to your code:

    var newInterval;
    // Event listeners
    $("#play").click(function() { 
        fetchImage(next); 
        newInterval = setInterval(function() { 
            fetchImage(next); 
        }, 1000); 
        return false;
    });

    $("#stop").click(function() { 
        clearInterval(newInterval); 
        return false;
    });

OTHER TIPS

You need to assign the setInterval function to a variable

var interval = setInterval(function () {});

clearInterval(interval)

I am assuming that is what you are after.

you gave the answer yourself

"it returns a value"

so let it return an alias for a value, a so called variable, ideally you declare it before so it doesnt throw undefined exception when you try to clear it an no #play was clicked befre

var xxx;
... 
$("#play").click(function() { fetchImage(next);xxx=setInterval(function() { fetchImage(next); }, 1000); return false;});
...
clearInterval(xxx)...

Have you ever used one of those "take a number" devices which extrude numbered slips of paper?

The return value from setInterval() is like a "Repeating Task ID#".

You shouldn't care how big the number is, but you should store it somewhere, and then you can pass it back into clearInterval() to tell the system which task to stop running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top