0

I have a function that posts a message to the parent component after 1 second.

setTimeout(function(){ 
 var widgetHeight =  getDocHeight();
 parent.postMessage(widgetHeight, hostURL);
}, 1000)

I want to refactor this so that I create a loop that checks the widgetHeight every 1/10th second and if it changed than post the message to the parent and stop the loop.

How can I do this?

Nope
  • 22,147
  • 7
  • 47
  • 72
Ant12345
  • 105
  • 3
  • It looks like you just have to use setInterval instead of setTimeout. setTimeout returns an object you can use to stop the interval to be executed – Deblaton Jean-Philippe Sep 12 '17 at 11:38
  • You can use `setInterval()` to perform an action at regular intervals. The return value of `setInterval()` is an identifier for that repeating action, which you can then use to cancel the action at a later time. – David Sep 12 '17 at 11:38
  • Possible duplicate of [How to exit from setInterval](https://stackoverflow.com/questions/1795100/how-to-exit-from-setinterval) – Nope Sep 12 '17 at 11:39

2 Answers2

0

Use an interval to create a repeatable timer.

        let timer
        let prevWidgetHeight = getDocHeight(); //Get initial height
        timer = setInterval(function(){ 
          let widgetHeight =  getDocHeight(); //Get the current height
          //Compare new height to previous height:
          if(widgetHeight !== prevWidgetHeight) { //If the current height is not the same as the initial height,
            prevWidgetHeight = widgetHeight 
            parent.postMessage(widgetHeight, hostURL); //Make the update
            clearInterval(timer) //Stop the timer
          }      
        }, 100) //100ms is 1/10th of second

This stops the loop once the height differs from the height set before starting the loop. Stopping it means new changes won't be passed on though.

Rob van Dijk
  • 722
  • 6
  • 15
0

First of all, you can't do this in a loop. Since Javascript is single threaded, doing this in a loop would lock the javascript process and effectively block anything from happening except checking for a value that will never change.

As other mentioned, the setInterval method could work... But since you're looking to update something when the document size change. You should instead use this:

window.addEventListener('resize', function (evt) {
    // do something on resize getDocHeight()
    var height = getDocHeight();
    ....

})

Note that here, I'm using directly window but it can be any other window object too.

Also more information on the resize event here: https://developer.mozilla.org/en-US/docs/Web/Events/resize

Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99