Categories
JavaScript Tips

JavaScript Tips — Pausing or Stopping Programs , Accessing Script Elements

Spread the love

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Pass Arguments to addEventListener Listener Function

There are a few ways to pass in arguments to an event listener function.

One way is to create another function and call that:

element.addEventListener("click", () => {
  foo(someVar);
}, false);

We just call foo inside the function with our arguments.

Also, we can set a property on an element and access it by writing:

const listener = (evt) => {
  window.alert(evt.currentTarget.foo);
}

element.addEventListener('click', listener, false);
element.foo = 'bar';

We get the element object with the currentTarget property.

Also, we can use bind to return a function with some arguments passed in:

function listener(foo, ev) {
  //...
}
element.addEventListener("click", listener.bind(null, foo), false);

We pass in foo as the 2nd argument of bind to pass it into the function.

Stop JavaScript Execution

There are a few ways to stop JavaScript programs.

One way is to throw an error.

For instance, we can write:

class `FatalError extends Error {}
throw new FatalError('fatal error');`

We can also use the return keyword in a function to stop it from running:

const foo = () => {
  `if(someEventHappened) {
     return;
  }
  //...
}`

Differences Between Deferred, Promise and Future in JavaScript

Deferred are objects that implement resolve , reject , and then .

We can create promises that call resolve , reject and returns an object that calls then .

Promise is a proxy object for storing the result of something that will be given in the future.

It also exposes a then method that accepts another target and returns a new promise.

A future is a deprecated term for either of those things.

Difference Between children and childNodes in JavaScript

children is a property of an element in JavaScript. It only returns child elements.

childNodes is a property of Node and can contain any node.

Combination of async, await and setTimeout

We can create a promise with setTimeout , then we can use async and await on it.

For instance, we can write:

const timeout = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const foo = async () => {
  await timeout(3000);
  //...
}

We created a promise with the Promise constructor which calls resolve to fulfill the promise.

ms is the delay duration in milliseconds.

Then we can use it anywhere else with async and await .

In Node apps, we can also use the util package by writing:

const sleep = require('util').promisify(setTimeout)

Convert an Integer to Binary in JavaScript

We can convert an integer to binary with the zero-fill right shift operator.

For instance, we can write:

(dec >>> 0).toString(2);

We convert the decimal number dec to a binary with the >>> operator, which shifts the given number of bits to the right.

In this case, we shift 0 bits to the right to make it an unsigned integer.

Then we convert it to a string with toString with argument 2 to convert it to a binary string.

If we have a positive integer, then we can just call toString(2) on the number.

Reference the script Tag that Loaded the Currently-Executing Script

We can use document.currentScript to return the script element that’s currently being processed.

It’s simple and reliable.

We don’t need to modify the script tag.

It also works with async scripts that have the defer or async attribute.

And it works with scripts that are inserted dynamically.

It doesn’t work with IE and scripts with type module .

We can also select a script by ID:

<script id="someScript">
const currentScript = document.getElementById('someScript');
</script>

It has the same benefits as document.currentScript and it’s universally supported.

But we’ve to add an ID and may cause weird behavior in rare cases.

Also, we can add a custom data attribute.

For instance, we can write:

<script data-name="someScript">
const currentScript = document.querySelector('script[data-name="someScript"]');
</script>

We get the script by the data-name attribute.

It’s simple and works with scripts inserted dynamically.

But it’s less widely supported than the id attribute.

Finally, we can also get a script by the src value.

For instance, we can write:

const script = document.querySelector('script[src="//example.com/script.js"]');

This doesn’t work on local scripts.

But it works with defer and async and it’s reliable in those situations.

It also works with scripts inserted dynamically.

Conclusion

There are a few ways to get the script element on a page.

We can pass arguments to an event listener with bind or calling another function.

There are a few ways to pause or stop the execution of JavaScript programs.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *