Poll javascript script widget

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Javascript Timers and Intervals made easy.

mtrpcic/polljs

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  So reuseaddr python socket

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.markdown

PollJS is a lightweight wrapper for the JavaScript Interval and Timer methods.

  • Lightweight (~1.5k)
  • Supports maximum attempt limits, fallbacks, and incremental interval times
  • Compatible with all major browsers (Tested on Firefox 3.6, Firefox 4.0, Firefox 5.0, Fireofox 6.0, Chrome 9, Opera 11, IE7, IE8, IE9)
  • Independant of all third party libraries, but plays nice with all of them

PollJS is simple to use. Every time you want to start an interval or timer, simply call the Poll.start method, and give it the appropriate configuration values:

To stop the interval, simply pass your defined name to the Poll.stop method:

You can also stop an interval from within it’s action by returning false:

PollJS accepts several configuration options:

 name: The defined name for your poller. This is the unique ID used to stop it in the future. action: This is the method to be executed whenever you tell it to happen. interval: This is how often the action will be run. Equivalent to calling the native `setInterval` function. start: This is when the action is first run. Equivalent to calling the native `setTimeout` function. increment: This works in conjunction with the 'interval` config option. It tells PollJS to increase the time between intervals by a particular value. attempts: This is the maximum number of attempts to be made. fallback: If the maximum number of attempts is reached, PollJS will execute a fallback action if you specify one. 

At least one of start or interval is required to set up a poller. If both are omitted, PollJS will raise an exception.

You can use all of the PollJS configuration options at once:

Poll.start(< name: "check_print_job", action: function()< //do some code here >, start: 5000, // Start this poller 5 seconds from now interval: 500, // Re-run the poller every 0.5 seconds increment: 200, // Increase the poll interval by 200ms every time it runs attempts: 5, fallback: function() < alert("Fallback"); >>); 

In the example above, all three timing options are provided, and play nicely together. Assuming the poller isn’t killed, it will run the action 5 times, at increasingly longer intervals.

To make a pull request, please do the following:

  • Mention what specific version of PollJS you were using when you encountered the issue/added the feature. This can be accessed by doing Poll.version in a debugger console
  • Provide a pastie or gist that demonstrates the bug/feature
  • Make sure to update the minified version of the source
  • Do not modify the Poll.version attribute. I will modify that manually when merging the request

This code is provided with no warranty. While I strive to maintain backwards compatibility, the code is still under active development. As this is the case, some revisions may break compatibility with earlier versions of the library. Please keep this in mind when using PollJS.

Copyright (c) 2011 Mike Trpcic, released under the MIT license.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A web component for a poll widget that is highly customizable and can be embedded into a web page.

firstprateek/poll-widget

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A web component for a poll widget that is highly customizable and can be easily embedded into a web page. Developed using LIT.

npm install poll-widget --save
// In index.js import PollWidget from 'poll-widget';
!DOCTYPE html> head> script src="./index.js">/script> /head> body> main> poll-widget voteAPI="http://localhost:3000/posts" requestAPI="http://localhost:3000/posts" height="200" width="600"> /poll-widget> /main> /body> /html>
/** * Poll widget: . * * A web component for a poll widget. * It can connect to a remote API to update and request poll results. * Poll results are retrieved via a GET request to the URL configured via the "resultsAPI" property * The API response needs to be in the following format: * *  * question: 'This is a poll!', * options: [ *  * id: 1, // Unique id, can be number or string * text: 'This is option 1', // String representing option text * votes: 500 // Number representing number of votes for this option * >, * . * ] * > * * A vote for an option is made via a PATCH request to the URL configured as the "voteAPI" property * The request body is the id of the option for which the user voted * * @property requestAPI - String. URL for retrieving the results * @property voteAPI - String. URL for casting a vote for user's choice * @property width - Number. width of the widget in pixels, if not defined, the width is set to 'auto' * @property height - Number. height of the widget in pixels, if not defined, the height is set to 'auto' * @property question - String. Question that is being polled * @property options - Array. List of options for the question. Array of objects. Each object should have an id and text * @property updateFrequency - Number. Minutes after which the poll results should be auto-updated, default 60 mins * @property timeAgo - Boolean. Show time ago the poll results were updated * * @fires submit - Indicates when the user submits a vote * * @cssproperty --poll-background-color - background color of the poll, default is purple * @cssproperty --poll-color - text color, default white * @cssproperty --poll-font-size - font size of text, title is 1.5 em, default 16px * @cssproperty --poll-border-radius - border radius of the poll widget, default 5px * @cssproperty --poll-bar-border-radius - border radius of the poll bars, default 2px * @cssproperty --poll-bar-color - color for the bars, default Cornflower Blue * @cssproperty --poll-vote-color - color for the votes */

About

A web component for a poll widget that is highly customizable and can be embedded into a web page.

Источник

JavaScript Polling

Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices. Sometimes there isn’t the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for it. Polling with JavaScript isn’t difficult but it’s not easy either. Let me show you a few implementations of JavaScript polling that you can add to your toolbox!

With Promises

Since the Promise API is implemented almost all browsers today, here’s a polling implementation using them:

// The polling function function poll(fn, timeout, interval) < var endTime = Number(new Date()) + (timeout || 2000); interval = interval || 100; var checkCondition = function(resolve, reject) < // If the condition is met, we're done! var result = fn(); if(result) < resolve(result); >// If the condition isn't met but the timeout hasn't elapsed, go again else if (Number(new Date()) < endTime) < setTimeout(checkCondition, interval, resolve, reject); >// Didn't match and too much time, reject! else < reject(new Error('timed out for ' + fn + ': ' + arguments)); >>; return new Promise(checkCondition); > // Usage: ensure element is visible poll(function() < return document.getElementById('lightbox').offsetWidth >0; >, 2000, 150).then(function() < // Polling done, now do something else! >).catch(function() < // Polling timed out, handle the error! >);

The code is structured easy enough to read but it’s mostly three-fold: the conditional function which signals polling success, a conditional failure which hasn’t timeout out, so we’ll run again, or a failure which has run past timeout which should return an error.

Without Deferreds

If you aren’t using Deferreds, no worry — polling is just about the same:

function poll(fn, callback, errback, timeout, interval) < var endTime = Number(new Date()) + (timeout || 2000); interval = interval || 100; (function p() < // If the condition is met, we're done! if(fn()) < callback(); >// If the condition isn't met but the timeout hasn't elapsed, go again else if (Number(new Date()) < endTime) < setTimeout(p, interval); >// Didn't match and too much time, reject! else < errback(new Error('timed out for ' + fn + ': ' + arguments)); >>)(); > // Usage: ensure element is visible poll( function() < return document.getElementById('lightbox').offsetWidth >0; >, function() < // Done, success callback >, function() < // Error, failure callback >);

The difference here is that there’s no return value — the callback functions take the place of the Deferred instance.

Polling isn’t necessarily a consequence of async coding but it has definitely increased in usage and importance due to our desire to write async code. During my time writing front-end functional tests with the Intern testing framework, I’ve used polling quite a bit both on the server and client sides. This technique will always have its place so make sure you have a snippet like this available.

Источник

Как создать опрос или голосование на сайте

Узнайте, как создать интерактивные опросы и голосования на вашем сайте с помощью HTML, плагинов и JavaScript!

Person creating an online poll

Создание опроса или голосования на сайте может быть полезным инструментом для получения обратной связи от пользователей и понимания их предпочтений. В этой статье мы рассмотрим основные методы реализации опросов и голосований на вашем сайте.

Простые HTML-формы

Один из простых способов создать опрос на сайте — использовать HTML-формы. Это позволяет собирать данные от пользователей без использования специализированных плагинов или сложных скриптов.

Пример опроса с использованием HTML-формы:

 

Какой ваш любимый цвет?

Красный
Зеленый
Синий

Использование плагинов и виджетов

😉 В ситуациях, когда вам нужно больше функциональности, чем простая HTML-форма, вы можете использовать плагины и виджеты для создания опросов и голосований. Такие инструменты обычно предлагают больше возможностей для кастомизации и управления результатами.

Некоторые популярные плагины и виджеты для создания опросов:

Создание опроса с помощью JavaScript и AJAX

Для более продвинутых пользователей и разработчиков можно создать опросы, используя JavaScript и AJAX. Этот подход позволяет создать более интерактивные опросы с динамическим обновлением контента без перезагрузки страницы.

Пример создания опроса с использованием JavaScript и AJAX:

 

Какой ваш любимый цвет?

Красный
Зеленый
Синий

Теперь вы знаете несколько способов создания опросов и голосований на сайте. Выберите подходящий для вас вариант и начните собирать обратную связь от пользователей. Удачи!

Источник

Оцените статью