Topic on Project:Support desk

Using js event listener and setTimeout in an extension

5
Summary by Supasaru

See my last comment in this thread.

Supasaru (talkcontribs)

Are there any restrictions on js functions allowed on MediaWiki? I'm asking because the function addEventListener() and setTimer don't seem to work.

The following js code works outside of MediaWiki (i.e. I troubleshot by creating a simple test.php file with the js script, and it works as intended.)

The following code is supposed to trigger every second and update a <nowiki><p></nowiki> tag on-screen, starting when the user clicks a button. Oddly, the function triggers on every button press, instead of once every second.

Here's the code: (I'm not using jQuery -- I copied an example online and didn't update it for jQuery.)


window.addEventListener( 'load', function ( ) {

var start = document .getElementById("start");

start.addEventListener( 'click', startTime );

});

function startTime( ) {

startWatch( );

// a few other things that hide / unhide some html elements

}

function startWatch( ) {

var x = document .getElementById("timer");

x.innerHTML = 'Time: ' + secs;

seconds++;

/* call the setTimeout( ) to keep the timer alive ! */

clearTime = setTimeout( "startWatch( )", 1000 );

}


Using MW version 1.30.0

Ciencia Al Poder (talkcontribs)

This is a JavaScript problem, not a MediaWiki problem. You may have more success asking in stackoverflow.

There are various flaws here. You use an undeclared and uninitialized "secs" variable, and then increment an also undeclared and uninitialized "seconds" variable. The function may simply error out, or print exactly the same on every run.

Supasaru (talkcontribs)

In my example code above, I didn't add all the variable declarations that I have in my actual .js file. (I thought I'd save a bit of space.) 'Seconds' is the incrementor and 'secs' is the output to HTML.

The reason I thought of asking here is that the script is working outside MediaWiki, but not in my MW Special page.

There isn't any thing else that would prevent the script from working in MW?

Ciencia Al Poder (talkcontribs)

Resource Loader minifies all scripts and puts them each inside a closure. This may affect the script depending on how it's coded.

Also, the scripts may be injected after the page has been loaded, and then attaching the startup to window.load may not work at all if the event has fired already. Use the jQuery replacements for that.

Supasaru (talkcontribs)

Gracias, Ciencia Al Poder.

I converted the code to jQuery and I had to debug the code.

What finally worked was changing

clearTime = setTimeout( "startWatch( )", 1000 );

to

clearTime = setTimeout( function() { startWatch( ); }, 1000 );


I've added this in case anybody else has any setTimeout issues.