简体   繁体   中英

setTimeout function issue when called multiple times

I have a "setTimeout" issue when a function is called multiple times.

When a user clicks on .icon, a function is called which will hide the div for the duration set as the third array parameter, then show it.

It works fine unless one clicks on an item and then clicks on another one. In that case the duration is set to the last one clicked for both items. I tried to generate a random variable instead of var cooldowndata but it didn't worked.

Data-id has the following : name, price and "timeout" duration.

<div class="actions">
    <div class="actionholder">
        <div class="box"><div class="subbox"></div><div class="icon" data-id="ItemA|33|15000">ItemA 15s.</div></div>
        <div class="box"><div class="subbox"></div><div class="icon"  data-id="ItemB|21|6000">ItemB 6s.</div></div>
        <div class="box"><div class="subbox"></div><div class="icon"  data-id="ItemC|45|28000">ItemC 28s.</div></div>
    </div>
</div>

$(".icon").bind("click",function() {
var data = $(this).data("id");
cooldown(data);
});

function cooldown(data)
{
var cooldowndata =  data.split('|'); 
actiontohide = $("div").find("[data-id='" + data + "']");
actiontohide.hide();
setTimeout(function() { actiontohide.show(); }, cooldowndata[2]);
}

As a for instance you can start with item B then item C, C will show up after 6 seconds instead of 28 seconds: http://jsfiddle.net/xpqbccn3/

Any pointers would be highly appreciated in understanding what I did wrong. Thank you.

actiontohide is a global, so each click overwrites it.

actiontohide = $("div").find("[data-id='" + data + "']");

should be

var actiontohide = $("div").find("[data-id='" + data + "']");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM