Search code examples
javascriptsettimeoutsetinterval

Timer to check frequently, after change value in Javascript


I want any time my submit value changed to Thanks do something for me, my submit id is #pollsubmit

So i tried to solve the problem with setTimeout( function()

But i think this is not a good solution and there may be a better solution to this problem

$("#pollsubmit").on("click", function() {
  setTimeout( function() { 
    if($("#pollsubmit").val() == 'Thanks'){
      // Do Something
    }else{
        setTimeout( function() { 
           if($("#pollsubmit").val() == 'Thanks'){
            // Do Something
            }else{
              setTimeout( function() { 
                 if($("#pollsubmit").val() == 'Thanks'){
                   // Do Something
                 }else{
                 }
              },1500);
            }
        },1500);
       }
  },1500);
});

The problem is, i do not know how many seconds it takes to change the value of a submit to Thanks


before ask this question i read this topic but my question is different, because the value of my button after clicking first changes to Loading and then to Thanks, in fact i need a timer to check frequently, after change value,

ex:

Button value is Submit after Click

First: Value changed to Loading

Second: Value changed to Thanks


Can anyone help me with this?

Thanks for any help


Solution

  • You could activate a timer and check frequently, after the change cancel it

     $("#pollsubmit").on("click", function() {
          const id = setInterval(() => {
            if ($("#pollsubmit").val() == 'Thanks') {
              clearInterval(id)
              //Do Something
            }
          }, 100);
        });