Question T3792
Visible to All Users

Timers in Custom WIdgets

created 5 years ago

I need a timer to run in a Custom widget to carry out an action periodically on one of the controls:

I have been advised to create the timer in afterRender: and destroy it in willUnmount: If I monitor the lifecycle of using the SUrvey Creator to place a widget, move between the tabs"Survey Designer" and "Test Survey" then all looks good.

This is probably a newbie issue but I am having difficulty setting the scope for the timer so that the timer created in afterRender can be destroyed in the different will Unmount function.

If I create the timer thus in afterRender:

Code
mapRefreshTimer = setInterval( () => { console.log("Do stuff"); }, 1000);

Then when I go to willUnmount then the function does not have access to the scope of the timer to run clearInterval.

I tried to define the var at the "function init(Survey: any)" level and altered the code thus;

Code
this.mapRefreshTimer = setInterval( () => { console.log("Do stuff"); }, 1000);

and in willUnmount:

Code
clearInterval(this.mapRefreshTimer);

This seemed to work but a timer remains running when the widget is deleted completely as a question. I presume I am scoping the timer incorrectly? Can you give me a pointer please?

Thanks,

Paul

Answers approved by surveyjs Support

created 5 years ago

Hello,

A timer in a custom widget should be created in the afterRender function and destroyed in the willUnmount function.
If for some reason widget has been destroyed, but the willUnmount function has not been called, please give us the steps to reproduce and we'll fix it.

Thanks, Serge
SurveyJS Team

    Show previous comments (10)
    S S
    SurveysInAngular 5 years ago

      Thanks…Can try that. Would prefer it if the widget could clean after itself in case I create problems later on with a pile of global variables.

      Something like a "questionDisplayed" callback would be great if it appeared at some point…

      Thanks again.

        Hello,

        The afterRender function and the willUnmount function of a custom widget are these callbacks indeed - DOM element created (to create and initialize a custom widget) and DOM element destroyed (to destroy a custom widget).

        As I said earlier than you switch from the "Test Survey" tab to the "Survey Designer" tab - the markup just become invisible and DOM nodes still alive. And your custom widget is not destroyed - that's why your timer still working.

        Thanks, Serge
        SurveyJS Team

          Thanks. The problem is leaflet has to resize the map after it is visible so the call outs you describe won't work.

          Paul