user2370950
user2370950

Reputation: 21

Stopping SetTimeout on mouse over and click

i am new in javascript and jquery

I made my own script that shows first span id 1 span id 2 spanid 3 etc I made somekind of loop so they would show each second the new span and close the other. But i want the loop to stop on mouse over on one of the span items. i tried

<span id="example_1" class="com_items">a</span>
<span id="example_2" class="com_items">b</span>
<span id="example_3" class="com_items">c</span>
<span id="example_4" class="com_items">d</span>
<span id="example_5" class="com_items">e</span>
<span id="example_6" class="com_items">f</span>
<script>
    function show_span(a){
            $('.com_items_but').css('background-color','#E84700');
        $('#example_but_'+a).css('background-color','#017095');
        $('.com_items').hide();
        $('#example_'+a).show();
}
function run_commer(){
    setTimeout(function() { show_span(1);}, 0); 
    setTimeout(function() { show_span(2);}, 1000); 
    setTimeout(function() { show_span(3);}, 2000); 
    setTimeout(function() { show_span(4);}, 3000); 
    setTimeout(function() { show_span(5);}, 4000); 
    setTimeout(function() { show_span(6);}, 5000); 
    setTimeout(run_commer, 6000);
}
run_commer();   
</script>

This is what i tried:

function stop_hover(){
var stop_h = 1; 
}
function run_commer(){
if(stop_h != 1){
    setTimeout(function() { show_span(1);}, 0); 
    setTimeout(function() { show_span(2);}, 1000); 
    setTimeout(function() { show_span(3);}, 2000); 
    setTimeout(function() { show_span(4);}, 3000); 
    setTimeout(function() { show_span(5);}, 4000); 
    setTimeout(function() { show_span(6);}, 5000); 
    setTimeout(run_commer, 6000);
    }
}

But i can see i'm doing something very wrong

Upvotes: 0

Views: 761

Answers (1)

BBagi
BBagi

Reputation: 2085

You need to assign the setTimeout to a variable, and then you can cancel it:

var timer = setTimeout(function() { 
        // Do something here...  
 }, 1000);

clearTimeout(timer);  //This cancels the first timer

Upvotes: 5

Related Questions