clearInterval outside of method containing setInte

2019-07-07 09:52发布

问题:

I have a messaging function that can be called several times on the same page. Each time it's called, a new message appears at the top of the screen and has a unique ID set by an incrementing global.

The general idea of the function is below:

var messageTimer = function(msgid, duration) {
  ...
  var interval = setInterval(
    function() {
    ...
    },
    duration
  )
};

In the code above, a new message is created and a timer applied. If the timer runs out, the message disappears. However, if the message is clicked on anywhere except the close button, the timer should stop and the message should stay until manually closed.

How do I find the interval ID of the message box clicked? There could be 3 other boxes simultaneously open.

$('body').on('click', '.msg', function() {

});

Since I only have a class to trigger the click by I'm thinking the only possible way to find this is to set an additional field to the ID of the message box? However this method seems unnecessary and messy.

回答1:

I would set a data property on the message which stores the interval ID:

var messageTimer = function(msgid, duration) {
  ...
  var interval = setInterval(
    function() {
    ...
    },
    duration
  );
  $("#" + msgid).data("i", interval);
};

Then recall it onclick of your message thingies:

$('body').on('click', '.msg', function() {
    clearInterval(parseInt($(this).data("i"), 10));
});


回答2:

Are you using html5? You could add a custom data attribute to your node. The javascript API for this feature is described here.