clearInterval outside of method containing setInterval

笑着哭i 提交于 2019-12-10 20:27:12

问题


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.



来源:https://stackoverflow.com/questions/9253938/clearinterval-outside-of-method-containing-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!